commit 768dc11d14aafca903f412193a1d6fff6a780ddf Author: EmotionChild Date: Mon Feb 21 21:40:09 2022 +1300 initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4ebb693 --- /dev/null +++ b/.gitignore @@ -0,0 +1,366 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +/warp-packer.exe +/SupportChild.exe diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/SupportChild.sln b/SupportChild.sln new file mode 100644 index 0000000..cc9d1b4 --- /dev/null +++ b/SupportChild.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32126.317 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SupportChild", "SupportChild\SupportChild.csproj", "{9124DF58-D261-4906-8ECA-D853DEBE07D4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9124DF58-D261-4906-8ECA-D853DEBE07D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9124DF58-D261-4906-8ECA-D853DEBE07D4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9124DF58-D261-4906-8ECA-D853DEBE07D4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9124DF58-D261-4906-8ECA-D853DEBE07D4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B2CD3447-A8BA-4B02-9E08-A75CBBD2BDCB} + EndGlobalSection +EndGlobal diff --git a/SupportChild/Commands/AddCommand.cs b/SupportChild/Commands/AddCommand.cs new file mode 100644 index 0000000..67ab598 --- /dev/null +++ b/SupportChild/Commands/AddCommand.cs @@ -0,0 +1,107 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class AddCommand : BaseCommandModule + { + [Command("add")] + [Description("Adds a user to a ticket.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "add")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the add command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.IsOpenTicket(command.Channel.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + string[] parsedArgs = Utilities.ParseIDs(command.RawArgumentString); + foreach (string parsedArg in parsedArgs) + { + if (!ulong.TryParse(parsedArg, out ulong userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + continue; + } + + DiscordMember mentionedMember; + try + { + mentionedMember = await command.Guild.GetMemberAsync(userID); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not find user on this server)" + }; + await command.RespondAsync(error); + continue; + } + + try + { + await command.Channel.AddOverwriteAsync(mentionedMember, Permissions.AccessChannels, Permissions.None); + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Added " + mentionedMember.Mention + " to ticket." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = mentionedMember.Mention + " was added to " + command.Channel.Mention + + " by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + catch (Exception) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not add <@" + parsedArg + "> to ticket, unknown error occured." + }; + await command.RespondAsync(message); + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AddMessageCommand.cs b/SupportChild/Commands/AddMessageCommand.cs new file mode 100644 index 0000000..af37808 --- /dev/null +++ b/SupportChild/Commands/AddMessageCommand.cs @@ -0,0 +1,77 @@ +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SupportChild.Commands +{ + public class AddMessageCommand : BaseCommandModule + { + [Command("addmessage")] + [Description("Adds a new message for the 'say' command.")] + public async Task OnExecute(CommandContext command, string identifier, [RemainingText] string message) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "addmessage")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the addmessage command but did not have permission."); + return; + } + + if (string.IsNullOrEmpty(message)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "No message specified." + }; + await command.RespondAsync(error); + return; + } + + if (Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is already a message with that identifier." + }; + await command.RespondAsync(error); + return; + } + + if (Database.AddMessage(identifier, command.Member.Id, message)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Message added." + }; + await command.RespondAsync(error); + return; + } + else + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed adding the message to the database." + }; + await command.RespondAsync(error); + return; + } + + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AddStaffCommand.cs b/SupportChild/Commands/AddStaffCommand.cs new file mode 100644 index 0000000..19a3041 --- /dev/null +++ b/SupportChild/Commands/AddStaffCommand.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class AddStaffCommand : BaseCommandModule + { + [Command("addstaff")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "addstaff")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the addstaff command but did not have permission."); + return; + } + + ulong userID; + string[] parsedArgs = Utilities.ParseIDs(commandArgs); + + if (!parsedArgs.Any()) + { + userID = command.Member.Id; + } + else if (!ulong.TryParse(parsedArgs[0], out userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + DiscordMember member; + try + { + member = await command.Guild.GetMemberAsync(userID); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not find user on this server)" + }; + await command.RespondAsync(error); + return; + } + + using (MySqlConnection c = Database.GetConnection()) + { + MySqlCommand cmd = Database.IsStaff(userID) ? new MySqlCommand(@"UPDATE staff SET name = @name WHERE user_id = @user_id", c) : new MySqlCommand(@"INSERT INTO staff (user_id, name) VALUES (@user_id, @name);", c); + + c.Open(); + cmd.Parameters.AddWithValue("@user_id", userID); + cmd.Parameters.AddWithValue("@name", member.DisplayName); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = member.Mention + " was added to staff." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = member.Mention + " was added to staff.\n", + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AssignCommand.cs b/SupportChild/Commands/AssignCommand.cs new file mode 100644 index 0000000..9a17423 --- /dev/null +++ b/SupportChild/Commands/AssignCommand.cs @@ -0,0 +1,135 @@ +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class AssignCommand : BaseCommandModule + { + [Command("assign")] + [Description("Assigns a staff member to a ticket.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "assign")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the assign command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + ulong staffID; + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedMessage.Any()) + { + staffID = command.Member.Id; + } + else if (!ulong.TryParse(parsedMessage[0], out staffID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + DiscordMember staffMember = null; + try + { + staffMember = await command.Guild.GetMemberAsync(staffID); + } + catch (NotFoundException) { } + + if (staffMember == null) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find user." + }; + await command.RespondAsync(error); + return; + } + + if (!Database.IsStaff(staffMember.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: User is not registered as staff." + }; + await command.RespondAsync(error); + return; + } + + if (!Database.AssignStaff(ticket, staffID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to assign " + staffMember.Mention + " to ticket." + }; + await command.RespondAsync(error); + return; + } + + DiscordEmbed feedback = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Assigned " + staffMember.Mention + " to ticket." + }; + await command.RespondAsync(feedback); + + if (Config.assignmentNotifications) + { + try + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been assigned to a support ticket: " + command.Channel.Mention + }; + await staffMember.SendMessageAsync(message); + } + catch (UnauthorizedException) { } + + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.Mention + " was was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/BlacklistCommand.cs b/SupportChild/Commands/BlacklistCommand.cs new file mode 100644 index 0000000..88cfb75 --- /dev/null +++ b/SupportChild/Commands/BlacklistCommand.cs @@ -0,0 +1,98 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class BlacklistCommand : BaseCommandModule + { + [Command("balcklist")] + [Description("Blacklists a user from opening tickets.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check is the user has permission to use this command. + if (!Config.HasPermission(command.Member, "blacklist")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the blacklist command but did not have permission."); + return; + } + + string[] parsedArgs = Utilities.ParseIDs(command.RawArgumentString); + foreach (string parsedArg in parsedArgs) + { + if (ulong.TryParse(parsedArg, out ulong userId)) + { + DiscordUser blacklistedUser = null; + try + { + blacklistedUser = await command.Client.GetUserAsync(userId); + } + catch (NotFoundException) { } + + if (blacklistedUser == null) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find user." + }; + await command.RespondAsync(message); + continue; + } + + try + { + if (!Database.Blacklist(blacklistedUser.Id, command.User.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = blacklistedUser.Mention + " is already blacklisted." + }; + await command.RespondAsync(error); + continue; + } + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Blacklisted " + blacklistedUser.Mention + "." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = blacklistedUser.Mention + " was blacklisted from opening tickets by " + command.Member.Mention + "." + }; + } + } + catch (Exception) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error occured while blacklisting " + blacklistedUser.Mention + "." + }; + await command.RespondAsync(message); + throw; + } + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/CloseCommand.cs b/SupportChild/Commands/CloseCommand.cs new file mode 100644 index 0000000..0c65939 --- /dev/null +++ b/SupportChild/Commands/CloseCommand.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class CloseCommand : BaseCommandModule + { + [Command("close")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "close")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the close command but did not have permission."); + return; + } + + ulong channelID = command.Channel.Id; + string channelName = command.Channel.Name; + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(channelID, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + // Build transcript + try + { + await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + }; + await command.RespondAsync(error); + throw; + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed embed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " closed by " + command.Member.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } + }; + + using (FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read)) + { + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(embed); + message.WithFiles(new Dictionary() { { Transcriber.GetFilename(ticket.id), file } }); + + await logChannel.SendMessageAsync(message); + } + } + + if (Config.closingNotifications) + { + DiscordEmbed embed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " which you opened has now been closed, check the transcript for more info.\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } + }; + + try + { + DiscordMember staffMember = await command.Guild.GetMemberAsync(ticket.creatorID); + + using (FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read)) + { + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(embed); + message.WithFiles(new Dictionary() { { Transcriber.GetFilename(ticket.id), file } }); + + await staffMember.SendMessageAsync(message); + } + } + catch (NotFoundException) { } + catch (UnauthorizedException) { } + } + + Database.ArchiveTicket(ticket); + + // Delete the channel and database entry + await command.Channel.DeleteAsync("Ticket closed."); + + Database.DeleteOpenTicket(ticket.id); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListAssignedCommand.cs b/SupportChild/Commands/ListAssignedCommand.cs new file mode 100644 index 0000000..19aaeae --- /dev/null +++ b/SupportChild/Commands/ListAssignedCommand.cs @@ -0,0 +1,76 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class ListAssignedCommand : BaseCommandModule + { + [Command("listassigned")] + [Aliases("la")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "listassigned")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the listassigned command but did not have permission."); + return; + } + + ulong staffID; + string[] parsedIDs = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedIDs.Any()) + { + staffID = command.Member.Id; + } + else if (!ulong.TryParse(parsedIDs[0], out staffID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + if (!Database.TryGetAssignedTickets(staffID, out List assignedTickets)) + { + DiscordEmbed error = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("User does not have any assigned tickets."); + await command.RespondAsync(error); + return; + } + + List listItems = new List(); + foreach (Database.Ticket ticket in assignedTickets) + { + listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + LinkedList messages = Utilities.ParseListIntoMessages(listItems); + foreach (string message in messages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Assigned tickets: ") + .WithColor(DiscordColor.Green) + .WithDescription(message); + await command.RespondAsync(channelInfo); + } + + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListCommand.cs b/SupportChild/Commands/ListCommand.cs new file mode 100644 index 0000000..9d9c2a3 --- /dev/null +++ b/SupportChild/Commands/ListCommand.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class ListCommand : BaseCommandModule + { + [Command("list")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "list")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the list command but did not have permission."); + return; + } + + ulong userID; + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedMessage.Any()) + { + userID = command.Member.Id; + } + else if (!ulong.TryParse(parsedMessage[0], out userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + if (Database.TryGetOpenTickets(userID, out List openTickets)) + { + List listItems = new List(); + foreach (Database.Ticket ticket in openTickets) + { + listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + ">\n"); + } + + LinkedList messages = Utilities.ParseListIntoMessages(listItems); + foreach (string message in messages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Open tickets: ") + .WithColor(DiscordColor.Green) + .WithDescription(message); + await command.RespondAsync(channelInfo); + } + } + else + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Green) + .WithDescription("User does not have any open tickets."); + await command.RespondAsync(channelInfo); + } + + if (Database.TryGetClosedTickets(userID, out List closedTickets)) + { + List listItems = new List(); + foreach (Database.Ticket ticket in closedTickets) + { + listItems.Add("**" + ticket.FormattedCreatedTime() + ":** Ticket " + ticket.id.ToString("00000") + "\n"); + } + + LinkedList messages = Utilities.ParseListIntoMessages(listItems); + foreach (string message in messages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Closed tickets: ") + .WithColor(DiscordColor.Red) + .WithDescription(message); + await command.RespondAsync(channelInfo); + } + } + else + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("User does not have any closed tickets."); + await command.RespondAsync(channelInfo); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListOldestCommand.cs b/SupportChild/Commands/ListOldestCommand.cs new file mode 100644 index 0000000..62dfd19 --- /dev/null +++ b/SupportChild/Commands/ListOldestCommand.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class ListOldestCommand : BaseCommandModule + { + [Command("listoldest")] + [Aliases("lo")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "listoldest")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the listoldest command but did not have permission."); + return; + } + + int listLimit = 20; + if (!string.IsNullOrEmpty(command.RawArgumentString?.Trim() ?? "")) + { + if (!int.TryParse(command.RawArgumentString?.Trim(), out listLimit) || listLimit < 5 || listLimit > 100) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid list amount. (Must be an integer between 5 and 100)" + }; + await command.RespondAsync(error); + return; + } + } + + if (!Database.TryGetOldestTickets(command.Member.Id, out List openTickets, listLimit)) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("Could not fetch any open tickets."); + await command.RespondAsync(channelInfo); + return; + } + + List listItems = new List(); + foreach (Database.Ticket ticket in openTickets) + { + listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + LinkedList messages = Utilities.ParseListIntoMessages(listItems); + foreach (string message in messages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("The " + openTickets.Count + " oldest open tickets: ") + .WithColor(DiscordColor.Green) + .WithDescription(message?.Trim()); + await command.RespondAsync(channelInfo); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListUnassignedCommand.cs b/SupportChild/Commands/ListUnassignedCommand.cs new file mode 100644 index 0000000..d41713d --- /dev/null +++ b/SupportChild/Commands/ListUnassignedCommand.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class ListUnassignedCommand : BaseCommandModule + { + [Command("listunassigned")] + [Aliases("lu")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "listunassigned")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the listunassigned command but did not have permission."); + return; + } + + if (!Database.TryGetAssignedTickets(0, out List unassignedTickets)) + { + DiscordEmbed response = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Green) + .WithDescription("There are no unassigned tickets."); + await command.RespondAsync(response); + } + + List listItems = new List(); + foreach (Database.Ticket ticket in unassignedTickets) + { + listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + LinkedList messages = Utilities.ParseListIntoMessages(listItems); + foreach (string message in messages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Unassigned tickets: ") + .WithColor(DiscordColor.Green) + .WithDescription(message?.Trim()); + await command.RespondAsync(channelInfo); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/MoveCommand.cs b/SupportChild/Commands/MoveCommand.cs new file mode 100644 index 0000000..f949148 --- /dev/null +++ b/SupportChild/Commands/MoveCommand.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class MoveCommand : BaseCommandModule + { + [Command("move")] + [Description("Move a ticket to another category.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "move")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the move command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + if (string.IsNullOrEmpty(command.RawArgumentString)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: No category provided." + }; + await command.RespondAsync(error); + return; + } + + IReadOnlyList channels = await command.Guild.GetChannelsAsync(); + IEnumerable categories = channels.Where(x => x.IsCategory); + DiscordChannel category = categories.FirstOrDefault(x => x.Name.StartsWith(command.RawArgumentString.Trim(), StringComparison.OrdinalIgnoreCase)); + + if (category == null) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find a category by that name." + }; + await command.RespondAsync(error); + return; + } + + if (command.Channel.Id == category.Id) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: The ticket is already in that category." + }; + await command.RespondAsync(error); + return; + } + + try + { + await command.Channel.ModifyAsync(modifiedAttributes => modifiedAttributes.Parent = category); + } + catch (UnauthorizedException) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Not authorized to move this ticket to that category." + }; + await command.RespondAsync(error); + return; + } + + DiscordEmbed feedback = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket was moved to " + category.Mention + }; + await command.RespondAsync(feedback); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/NewCommand.cs b/SupportChild/Commands/NewCommand.cs new file mode 100644 index 0000000..2270c91 --- /dev/null +++ b/SupportChild/Commands/NewCommand.cs @@ -0,0 +1,150 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class NewCommand : BaseCommandModule + { + [Command("new")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "new")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the new command but did not have permission."); + return; + } + + // Check if user is blacklisted + if (Database.IsBlacklisted(command.User.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You are banned from opening tickets." + }; + await command.RespondAsync(error); + return; + } + + if (Database.IsOpenTicket(command.Channel.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You cannot use this command in a ticket channel." + }; + await command.RespondAsync(error); + return; + } + + DiscordChannel category = command.Guild.GetChannel(Config.ticketCategory); + DiscordChannel ticketChannel; + + try + { + ticketChannel = await command.Guild.CreateChannelAsync("ticket", ChannelType.Text, category); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error occured while creating ticket, " + command.Member.Mention + + "!\nIs the channel limit reached in the server or ticket category?" + }; + await command.RespondAsync(error); + return; + } + + if (ticketChannel == null) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error occured while creating ticket, " + command.Member.Mention + + "!\nIs the channel limit reached in the server or ticket category?" + }; + await command.RespondAsync(error); + return; + } + + ulong staffID = 0; + if (Config.randomAssignment) + { + staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0; + } + + long id = Database.NewTicket(command.Member.Id, staffID, ticketChannel.Id); + string ticketID = id.ToString("00000"); + await ticketChannel.ModifyAsync(modifiedAttributes => modifiedAttributes.Name = "ticket-" + ticketID); + await ticketChannel.AddOverwriteAsync(command.Member, Permissions.AccessChannels, Permissions.None); + + await ticketChannel.SendMessageAsync("Hello, " + command.Member.Mention + "!\n" + Config.welcomeMessage); + + // Refreshes the channel as changes were made to it above + ticketChannel = command.Guild.GetChannel(ticketChannel.Id); + + if (staffID != 0) + { + DiscordEmbed assignmentMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket was randomly assigned to <@" + staffID + ">." + }; + await ticketChannel.SendMessageAsync(assignmentMessage); + + if (Config.assignmentNotifications) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been randomly assigned to a newly opened support ticket: " + + ticketChannel.Mention + }; + + try + { + DiscordMember staffMember = await command.Guild.GetMemberAsync(staffID); + await staffMember.SendMessageAsync(message); + } + catch (NotFoundException) { } + catch (UnauthorizedException) { } + } + } + + DiscordEmbed response = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket opened, " + command.Member.Mention + "!\n" + ticketChannel.Mention + }; + await command.RespondAsync(response); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticketChannel.Mention + " opened by " + command.Member.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "Ticket " + ticketID } + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RandomAssignCommand.cs b/SupportChild/Commands/RandomAssignCommand.cs new file mode 100644 index 0000000..7c92598 --- /dev/null +++ b/SupportChild/Commands/RandomAssignCommand.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class RandomAssignCommand : BaseCommandModule + { + [Command("rassign")] + [Description("Randomly assigns a staff member to a ticket.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArguments) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "rassign")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the rassign command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + // Get a random staff member who is verified to have the correct role if applicable + DiscordMember staffMember = await GetRandomVerifiedStaffMember(command, ticket); + if (staffMember == null) + { + return; + } + + // Attempt to assign the staff member to the ticket + if (!Database.AssignStaff(ticket, staffMember.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to assign " + staffMember.Mention + " to ticket." + }; + await command.RespondAsync(error); + return; + } + + // Respond that the command was successful + DiscordEmbed feedback = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Randomly assigned " + staffMember.Mention + " to ticket." + }; + await command.RespondAsync(feedback); + + // Send a notification to the staff member if applicable + if (Config.assignmentNotifications) + { + try + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been randomly assigned to a support ticket: " + command.Channel.Mention + }; + await staffMember.SendMessageAsync(message); + } + catch (UnauthorizedException) { } + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.Mention + " was was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + + private async Task GetRandomVerifiedStaffMember(CommandContext command, Database.Ticket ticket) + { + if (command.RawArguments.Any()) // An argument was provided, check if this can be parsed into a role + { + ulong roleID = 0; + + // Try to parse either discord mention or ID + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + if (!ulong.TryParse(parsedMessage[0], out roleID)) + { + // Try to find role by name + roleID = Utilities.GetRoleByName(command.Guild, command.RawArgumentString)?.Id ?? 0; + } + + // Check if a role was found + if (roleID == 0) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find a role by that name/ID." + }; + await command.RespondAsync(error); + return null; + } + + // Check if role rassign should override staff's active status + List staffMembers = Config.randomAssignRoleOverride + ? Database.GetAllStaff(ticket.assignedStaffID) + : Database.GetActiveStaff(ticket.assignedStaffID); + + // Randomize the list before checking for roles in order to reduce number of API calls + staffMembers = Utilities.RandomizeList(staffMembers); + + // Get the first staff member that has the role + foreach (Database.StaffMember sm in staffMembers) + { + try + { + DiscordMember verifiedMember = await command.Guild.GetMemberAsync(sm.userID); + if (verifiedMember?.Roles?.Any(role => role.Id == roleID) ?? false) + { + return verifiedMember; + } + } + catch (Exception e) + { + command.Client.Logger.Log(LogLevel.Information, e, "Error occured trying to find a staff member in the rassign command."); + } + } + } + else // No role was specified, any active staff will be picked + { + Database.StaffMember staffEntry = Database.GetRandomActiveStaff(ticket.assignedStaffID); + if (staffEntry == null) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: There are no other staff members to choose from." + }; + await command.RespondAsync(error); + return null; + } + + // Get the staff member from discord + try + { + return await command.Guild.GetMemberAsync(staffEntry.userID); + } + catch (NotFoundException) { } + } + + // Send a more generic error if we get to this point and still haven't found the staff member + DiscordEmbed err = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find an applicable staff member." + }; + await command.RespondAsync(err); + return null; + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ReloadCommand.cs b/SupportChild/Commands/ReloadCommand.cs new file mode 100644 index 0000000..597c4fc --- /dev/null +++ b/SupportChild/Commands/ReloadCommand.cs @@ -0,0 +1,38 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class ReloadCommand : BaseCommandModule + { + [Command("reload")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "reload")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the reload command but did not have permission."); + return; + } + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Reloading bot application..." + }; + await command.RespondAsync(message); + Console.WriteLine("Reloading bot..."); + SupportChild.instance.Reload(); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RemoveMessageCommand.cs b/SupportChild/Commands/RemoveMessageCommand.cs new file mode 100644 index 0000000..cacb1bc --- /dev/null +++ b/SupportChild/Commands/RemoveMessageCommand.cs @@ -0,0 +1,66 @@ +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SupportChild.Commands +{ + public class RemoveMessageCommand : BaseCommandModule + { + [Command("removemessage")] + [Description("Removes a message from the 'say' command.")] + public async Task OnExecute(CommandContext command, string identifier) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "removemessage")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the removemessage command but did not have permission."); + return; + } + + if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is no message with that identifier." + }; + await command.RespondAsync(error); + return; + } + + if (Database.RemoveMessage(identifier)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Message removed." + }; + await command.RespondAsync(error); + return; + } + else + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed removing the message from the database." + }; + await command.RespondAsync(error); + return; + } + + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RemoveStaffCommand.cs b/SupportChild/Commands/RemoveStaffCommand.cs new file mode 100644 index 0000000..6bd51dd --- /dev/null +++ b/SupportChild/Commands/RemoveStaffCommand.cs @@ -0,0 +1,104 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class RemoveStaffCommand : BaseCommandModule + { + [Command("removestaff")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "removestaff")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the removestaff command but did not have permission."); + return; + } + + ulong userID; + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedMessage.Any()) + { + userID = command.Member.Id; + } + else if (!ulong.TryParse(parsedMessage[0], out userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + try + { + await command.Client.GetUserAsync(userID); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not find user on Discord)" + }; + await command.RespondAsync(error); + return; + } + + if (!Database.IsStaff(userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "User is already not registered as staff." + }; + await command.RespondAsync(error); + return; + } + + using (MySqlConnection c = Database.GetConnection()) + { + c.Open(); + MySqlCommand deletion = new MySqlCommand(@"DELETE FROM staff WHERE user_id=@user_id", c); + deletion.Parameters.AddWithValue("@user_id", userID); + deletion.Prepare(); + deletion.ExecuteNonQuery(); + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "User was removed from staff." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "User was removed from staff.\n", + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SayCommand.cs b/SupportChild/Commands/SayCommand.cs new file mode 100644 index 0000000..e95fe7c --- /dev/null +++ b/SupportChild/Commands/SayCommand.cs @@ -0,0 +1,96 @@ +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace SupportChild.Commands +{ + public class SayCommand : BaseCommandModule + { + [Command("say")] + [Cooldown(1, 2, CooldownBucketType.User)] + [Description("Prints a message with information from staff.")] + public async Task OnExecute(CommandContext command, string identifier) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "say")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the say command but did not have permission."); + return; + } + + if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message message)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is no message with that identifier." + }; + await command.RespondAsync(error); + return; + } + + DiscordEmbed reply = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message.message + }; + await command.RespondAsync(reply); + } + + [Command("say")] + [Cooldown(1, 2.0, CooldownBucketType.Channel)] + [Description("Prints a list of staff messages.")] + public async Task OnExecute(CommandContext command) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "say")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the say command but did not have permission."); + return; + } + + + List messages = Database.GetAllMessages(); + if (!messages.Any()) + { + DiscordEmbed error = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("There are no messages registered."); + await command.RespondAsync(error); + return; + } + + List listItems = new List(); + foreach (Database.Message message in messages) + { + listItems.Add("**" + message.identifier + "** Added by <@" + message.userID + ">\n"); + } + + LinkedList listMessages = Utilities.ParseListIntoMessages(listItems); + foreach (string listMessage in listMessages) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Available messages: ") + .WithColor(DiscordColor.Green) + .WithDescription(listMessage); + await command.RespondAsync(channelInfo); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SetSummaryCommand.cs b/SupportChild/Commands/SetSummaryCommand.cs new file mode 100644 index 0000000..019461d --- /dev/null +++ b/SupportChild/Commands/SetSummaryCommand.cs @@ -0,0 +1,63 @@ +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class SetSummaryCommand : BaseCommandModule + { + [Command("setsummary")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "setsummary")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the setsummary command but did not have permission."); + return; + } + + ulong channelID = command.Channel.Id; + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + string sumarry = command.Message.Content.Replace(Config.prefix + "setsummary", "").Trim(); + + using (MySqlConnection c = Database.GetConnection()) + { + c.Open(); + MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET summary = @summary WHERE channel_id = @channel_id", c); + update.Parameters.AddWithValue("@summary", sumarry); + update.Parameters.AddWithValue("@channel_id", channelID); + update.Prepare(); + update.ExecuteNonQuery(); + update.Dispose(); + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Summary set." + }; + await command.RespondAsync(message); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SetTicketCommand.cs b/SupportChild/Commands/SetTicketCommand.cs new file mode 100644 index 0000000..bbbf7ce --- /dev/null +++ b/SupportChild/Commands/SetTicketCommand.cs @@ -0,0 +1,98 @@ +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class SetTicketCommand : BaseCommandModule + { + [Command("setticket")] + [Description("Turns a channel into a ticket, warning: this will let anyone with write access delete the channel using the close command.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + using (MySqlConnection c = Database.GetConnection()) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "setticket")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the setticket command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (Database.IsOpenTicket(command.Channel.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is already a ticket." + }; + await command.RespondAsync(error); + return; + } + + ulong userID; + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedMessage.Any()) + { + userID = command.Member.Id; + } + else if (!ulong.TryParse(parsedMessage[0], out userID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + DiscordUser user = await command.Client.GetUserAsync(userID); + + if (user == null) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention." + }; + await command.RespondAsync(error); + return; + } + + long id = Database.NewTicket(userID, 0, command.Channel.Id); + string ticketID = id.ToString("00000"); + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Channel has been designated ticket " + ticketID + "." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = command.Channel.Mention + " has been designated ticket " + ticketID + " by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/StatusCommand.cs b/SupportChild/Commands/StatusCommand.cs new file mode 100644 index 0000000..c0e4f33 --- /dev/null +++ b/SupportChild/Commands/StatusCommand.cs @@ -0,0 +1,41 @@ +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class StatusCommand : BaseCommandModule + { + [Command("status")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "status")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the status command but did not have permission."); + return; + } + + long openTickets = Database.GetNumberOfTickets(); + long closedTickets = Database.GetNumberOfClosedTickets(); + + DiscordEmbed botInfo = new DiscordEmbedBuilder() + .WithAuthor("EmotionChild/SupportChild @ GitHub", "https://github.com/EmotionChild/SupportChild", "https://cdn.discordapp.com/attachments/765441543100170271/919729931922051072/Ellise_Concept_2.png") + .WithTitle("Bot information") + .WithColor(DiscordColor.Cyan) + .AddField("Version:", SupportChild.GetVersion(), false) + .AddField("Open tickets:", openTickets + "", true) + .AddField("Closed tickets (1.1.0+ tickets only):", closedTickets + " ", true); + await command.RespondAsync(botInfo); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SummaryCommand.cs b/SupportChild/Commands/SummaryCommand.cs new file mode 100644 index 0000000..221d7e1 --- /dev/null +++ b/SupportChild/Commands/SummaryCommand.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class SummaryCommand : BaseCommandModule + { + [Command("summary")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "summary")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the summary command but did not have permission."); + return; + } + + if (Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Channel information") + .WithColor(DiscordColor.Cyan) + .AddField("Ticket number:", ticket.id.ToString(), true) + .AddField("Ticket creator:", $"<@{ticket.creatorID}>", true) + .AddField("Assigned staff:", ticket.assignedStaffID == 0 ? "Unassigned." : $"<@{ticket.assignedStaffID}>", true) + .AddField("Creation time:", ticket.createdTime.ToString(Config.timestampFormat), true) + .AddField("Summary:", string.IsNullOrEmpty(ticket.summary) ? "No summary." : ticket.summary, false); + await command.RespondAsync(channelInfo); + } + else + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ToggleActiveCommand.cs b/SupportChild/Commands/ToggleActiveCommand.cs new file mode 100644 index 0000000..2708892 --- /dev/null +++ b/SupportChild/Commands/ToggleActiveCommand.cs @@ -0,0 +1,78 @@ +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class ToggleActiveCommand : BaseCommandModule + { + [Command("toggleactive")] + [Aliases("ta")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + using (MySqlConnection c = Database.GetConnection()) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "toggleactive")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the toggleactive command but did not have permission."); + return; + } + + ulong staffID; + string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString); + + if (!parsedMessage.Any()) + { + staffID = command.Member.Id; + } + else if (!ulong.TryParse(parsedMessage[0], out staffID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid ID/Mention. (Could not convert to numerical)" + }; + await command.RespondAsync(error); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetStaff(staffID, out Database.StaffMember staffMember)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You have not been registered as staff." + }; + await command.RespondAsync(error); + return; + } + + c.Open(); + MySqlCommand update = new MySqlCommand(@"UPDATE staff SET active = @active WHERE user_id = @user_id", c); + update.Parameters.AddWithValue("@user_id", staffID); + update.Parameters.AddWithValue("@active", !staffMember.active); + update.Prepare(); + update.ExecuteNonQuery(); + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = staffMember.active ? "Staff member is now set as inactive and will no longer be randomly assigned any support tickets." : "Staff member is now set as active and will be randomly assigned support tickets again." + }; + await command.RespondAsync(message); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/TranscriptCommand.cs b/SupportChild/Commands/TranscriptCommand.cs new file mode 100644 index 0000000..9be4e50 --- /dev/null +++ b/SupportChild/Commands/TranscriptCommand.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class TranscriptCommand : BaseCommandModule + { + [Command("transcript")] + [Cooldown(1, 5, CooldownBucketType.User)] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "transcript")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the transcript but did not have permission."); + return; + } + + Database.Ticket ticket; + string strippedMessage = command.Message.Content.Replace(Config.prefix, ""); + string[] parsedMessage = strippedMessage.Replace("<@!", "").Replace("<@", "").Replace(">", "").Split(); + + // If there are no arguments use current channel + if (parsedMessage.Length < 2) + { + if (Database.TryGetOpenTicket(command.Channel.Id, out ticket)) + { + try + { + await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + }; + await command.RespondAsync(error); + throw; + } + } + else + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + } + else + { + // Check if argument is numerical, if not abort + if (!uint.TryParse(parsedMessage[1], out uint ticketID)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Argument must be a number." + }; + await command.RespondAsync(error); + return; + } + + // If the ticket is still open, generate a new fresh transcript + if (Database.TryGetOpenTicketByID(ticketID, out ticket) && ticket?.creatorID == command.Member.Id) + { + try + { + await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); + } + catch (Exception) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + }; + await command.RespondAsync(error); + throw; + } + + } + // If there is no open or closed ticket, send an error. If there is a closed ticket we will simply use the old transcript from when the ticket was closed. + else if (!Database.TryGetClosedTicket(ticketID, out ticket) || (ticket?.creatorID != command.Member.Id && !Database.IsStaff(command.Member.Id))) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find a closed ticket with that number which you opened." + (Config.HasPermission(command.Member, "list") ? "\n(Use the " + Config.prefix + "list command to see all your tickets)" : "") + }; + await command.RespondAsync(error); + return; + } + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed embed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " transcript generated by " + command.Member.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + command.Channel.Name } + }; + + using (FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read)) + { + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(embed); + message.WithFiles(new Dictionary() { { Transcriber.GetFilename(ticket.id), file } }); + + await logChannel.SendMessageAsync(message); + } + } + + try + { + // Send transcript privately + DiscordEmbed directMessageEmbed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Transcript generated, " + command.Member.Mention + "!\n" + }; + + using (FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read)) + { + DiscordMessageBuilder directMessage = new DiscordMessageBuilder(); + directMessage.WithEmbed(directMessageEmbed); + directMessage.WithFiles(new Dictionary() { { Transcriber.GetFilename(ticket.id), file } }); + + await command.Member.SendMessageAsync(directMessage); + } + + // Respond to message directly + DiscordEmbed response = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Transcript sent, " + command.Member.Mention + "!\n" + }; + await command.RespondAsync(response); + } + catch (UnauthorizedException) + { + // Send transcript privately + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Not allowed to send direct message to you, " + command.Member.Mention + ", please check your privacy settings.\n" + }; + await command.RespondAsync(error); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/UnassignCommand.cs b/SupportChild/Commands/UnassignCommand.cs new file mode 100644 index 0000000..22962c0 --- /dev/null +++ b/SupportChild/Commands/UnassignCommand.cs @@ -0,0 +1,71 @@ +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class UnassignCommand : BaseCommandModule + { + [Command("unassign")] + [Description("Unassigns a staff member from a ticket.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "unassign")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the unassign command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + if (!Database.UnassignStaff(ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to unassign staff from ticket." + }; + await command.RespondAsync(error); + return; + } + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Unassigned staff from ticket." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Staff was unassigned from " + command.Channel.Mention + " by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/UnblacklistCommand.cs b/SupportChild/Commands/UnblacklistCommand.cs new file mode 100644 index 0000000..f123f8c --- /dev/null +++ b/SupportChild/Commands/UnblacklistCommand.cs @@ -0,0 +1,99 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands +{ + public class UnblacklistCommand : BaseCommandModule + { + [Command("unblacklist")] + [Description("Un-blacklists a user from from opening tickets.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "unblacklist")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the unblacklist command but did not have permission."); + return; + } + + string[] words = Utilities.ParseIDs(command.RawArgumentString); + foreach (string word in words) + { + if (ulong.TryParse(word, out ulong userId)) + { + DiscordUser blacklistedUser = null; + try + { + blacklistedUser = await command.Client.GetUserAsync(userId); + } + catch (NotFoundException) { } + + if (blacklistedUser == null) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find user." + }; + await command.RespondAsync(message); + continue; + } + + try + { + if (!Database.Unblacklist(blacklistedUser.Id)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = blacklistedUser.Mention + " is not blacklisted." + }; + await command.RespondAsync(error); + continue; + } + + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Removed " + blacklistedUser.Mention + " from blacklist." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = blacklistedUser.Mention + " was unblacklisted from opening tickets by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + catch (Exception) + { + DiscordEmbed message = new DiscordEmbedBuilder() + { + Color = DiscordColor.Red, + Description = "Error occured while removing " + blacklistedUser.Mention + " from blacklist." + }; + await command.RespondAsync(message); + throw; + } + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/UnsetTicketCommand.cs b/SupportChild/Commands/UnsetTicketCommand.cs new file mode 100644 index 0000000..2884f94 --- /dev/null +++ b/SupportChild/Commands/UnsetTicketCommand.cs @@ -0,0 +1,70 @@ +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using Microsoft.Extensions.Logging; +using MySql.Data.MySqlClient; + +namespace SupportChild.Commands +{ + public class UnsetTicketCommand : BaseCommandModule + { + [Command("unsetticket")] + [Description( + "Deletes a channel from the ticket system without deleting the channel.")] + public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs) + { + using (MySqlConnection c = Database.GetConnection()) + { + // Check if the user has permission to use this command. + if (!Config.HasPermission(command.Member, "unsetticket")) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "You do not have permission to use this command." + }; + await command.RespondAsync(error); + command.Client.Logger.Log(LogLevel.Information, "User tried to use the unsetticket command but did not have permission."); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }; + await command.RespondAsync(error); + return; + } + + c.Open(); + MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE channel_id=@channel_id", c); + deletion.Parameters.AddWithValue("@channel_id", command.Channel.Id); + deletion.Prepare(); + deletion.ExecuteNonQuery(); + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Channel has been undesignated as a ticket." + }; + await command.RespondAsync(message); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = command.Channel.Mention + " has been undesignated as a ticket by " + command.Member.Mention + "." + }; + await logChannel.SendMessageAsync(logMessage); + } + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Config.cs b/SupportChild/Config.cs new file mode 100644 index 0000000..6b27498 --- /dev/null +++ b/SupportChild/Config.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using DSharpPlus.Entities; +using Newtonsoft.Json.Linq; +using SupportChild.Properties; +using YamlDotNet.Serialization; + +namespace SupportChild +{ + internal static class Config + { + internal static string token = ""; + internal static string prefix = ""; + internal static ulong logChannel; + internal static ulong ticketCategory; + internal static ulong reactionMessage; + internal static string welcomeMessage = ""; + internal static string logLevel = "Information"; + internal static string timestampFormat = "yyyy-MMM-dd HH:mm"; + internal static bool randomAssignment = false; + internal static bool randomAssignRoleOverride = false; // TODO: Implement + internal static string presenceType = "Playing"; + internal static string presenceText = ""; + + internal static bool ticketUpdatedNotifications = false; + internal static double ticketUpdatedNotificationDelay = 0.0; + internal static bool assignmentNotifications = false; + internal static bool closingNotifications = false; + + internal static string hostName = "127.0.0.1"; + internal static int port = 3306; + internal static string database = "supportbot"; + internal static string username = "supportbot"; + internal static string password = ""; + + private static readonly Dictionary permissions = new Dictionary + { + // Public commands + { "close", new ulong[]{ } }, + { "list", new ulong[]{ } }, + { "new", new ulong[]{ } }, + { "say", new ulong[]{ } }, + { "status", new ulong[]{ } }, + { "summary", new ulong[]{ } }, + { "transcript", new ulong[]{ } }, + // Moderator commands + { "add", new ulong[]{ } }, + { "addmessage", new ulong[]{ } }, + { "assign", new ulong[]{ } }, + { "blacklist", new ulong[]{ } }, + { "listassigned", new ulong[]{ } }, + { "listoldest", new ulong[]{ } }, + { "listunassigned", new ulong[]{ } }, + { "move", new ulong[]{ } }, + { "rassign", new ulong[]{ } }, + { "removemessage", new ulong[]{ } }, + { "setsummary", new ulong[]{ } }, + { "toggleactive", new ulong[]{ } }, + { "unassign", new ulong[]{ } }, + { "unblacklist", new ulong[]{ } }, + // Admin commands + { "addstaff", new ulong[]{ } }, + { "reload", new ulong[]{ } }, + { "removestaff", new ulong[]{ } }, + { "setticket", new ulong[]{ } }, + { "unsetticket", new ulong[]{ } }, + }; + + public static void LoadConfig() + { + // Writes default config to file if it does not already exist + if (!File.Exists("./config.yml")) + { + File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config)); + } + + // Reads config contents into FileStream + FileStream stream = File.OpenRead("./config.yml"); + + // Converts the FileStream into a YAML object + IDeserializer deserializer = new DeserializerBuilder().Build(); + object yamlObject = deserializer.Deserialize(new StreamReader(stream)); + + // Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name + ISerializer serializer = new SerializerBuilder().JsonCompatible().Build(); + JObject json = JObject.Parse(serializer.Serialize(yamlObject)); + + // Sets up the bot + token = json.SelectToken("bot.token").Value() ?? ""; + prefix = json.SelectToken("bot.prefix").Value() ?? ""; + logChannel = json.SelectToken("bot.log-channel").Value(); + ticketCategory = json.SelectToken("bot.ticket-category")?.Value() ?? 0; + reactionMessage = json.SelectToken("bot.reaction-message")?.Value() ?? 0; + welcomeMessage = json.SelectToken("bot.welcome-message").Value() ?? ""; + logLevel = json.SelectToken("bot.console-log-level").Value() ?? ""; + timestampFormat = json.SelectToken("bot.timestamp-format").Value() ?? "yyyy-MM-dd HH:mm"; + randomAssignment = json.SelectToken("bot.random-assignment")?.Value() ?? false; + randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value() ?? false; + presenceType = json.SelectToken("bot.presence-type")?.Value() ?? "Playing"; + presenceText = json.SelectToken("bot.presence-text")?.Value() ?? ""; + + ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value() ?? false; + ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value() ?? 0.0; + assignmentNotifications = json.SelectToken("notifications.assignment")?.Value() ?? false; + closingNotifications = json.SelectToken("notifications.closing")?.Value() ?? false; + + // Reads database info + hostName = json.SelectToken("database.address")?.Value() ?? ""; + port = json.SelectToken("database.port")?.Value() ?? 3306; + database = json.SelectToken("database.name")?.Value() ?? "supportbot"; + username = json.SelectToken("database.user")?.Value() ?? "supportbot"; + password = json.SelectToken("database.password")?.Value() ?? ""; + + timestampFormat = timestampFormat.Trim(); + + foreach (KeyValuePair node in permissions.ToList()) + { + try + { + permissions[node.Key] = json.SelectToken("permissions." + node.Key).Value().Values().ToArray(); + } + catch (ArgumentNullException) + { + Console.WriteLine("Permission node '" + node.Key + "' was not found in the config, using default value: []"); + } + } + } + + /// + /// Checks whether a user has a specific permission. + /// + /// The Discord user to check. + /// The permission name to check. + /// + public static bool HasPermission(DiscordMember member, string permission) + { + return member.Roles.Any(role => permissions[permission].Contains(role.Id)) || permissions[permission].Contains(member.Guild.Id); + } + } +} \ No newline at end of file diff --git a/SupportChild/Database.cs b/SupportChild/Database.cs new file mode 100644 index 0000000..4dd374b --- /dev/null +++ b/SupportChild/Database.cs @@ -0,0 +1,691 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using MySql.Data.MySqlClient; + +namespace SupportChild +{ + public static class Database + { + private static string connectionString = ""; + + private static Random random = new Random(); + + public static void SetConnectionString(string host, int port, string database, string username, string password) + { + connectionString = "server=" + host + + ";database=" + database + + ";port=" + port + + ";userid=" + username + + ";password=" + password; + } + public static MySqlConnection GetConnection() + { + return new MySqlConnection(connectionString); + } + public static long GetNumberOfTickets() + { + try + { + using (MySqlConnection c = GetConnection()) + { + MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c); + c.Open(); + return (long)countTickets.ExecuteScalar(); + } + } + catch (Exception e) + { + Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); + } + + return -1; + } + public static long GetNumberOfClosedTickets() + { + try + { + using (MySqlConnection c = GetConnection()) + { + MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c); + c.Open(); + return (long)countTickets.ExecuteScalar(); + } + } + catch (Exception e) + { + Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); + } + + return -1; + } + public static void SetupTables() + { + using (MySqlConnection c = GetConnection()) + { + MySqlCommand createTickets = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS tickets(" + + "id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," + + "created_time DATETIME NOT NULL," + + "creator_id BIGINT UNSIGNED NOT NULL," + + "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + + "summary VARCHAR(5000) NOT NULL," + + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + + "INDEX(created_time, assigned_staff_id, channel_id))", + c); + MySqlCommand createTicketHistory = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS ticket_history(" + + "id INT UNSIGNED NOT NULL PRIMARY KEY," + + "created_time DATETIME NOT NULL," + + "closed_time DATETIME NOT NULL," + + "creator_id BIGINT UNSIGNED NOT NULL," + + "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + + "summary VARCHAR(5000) NOT NULL," + + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + + "INDEX(created_time, closed_time, channel_id))", + c); + MySqlCommand createBlacklisted = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS blacklisted_users(" + + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + + "time DATETIME NOT NULL," + + "moderator_id BIGINT UNSIGNED NOT NULL," + + "INDEX(user_id, time))", + c); + MySqlCommand createStaffList = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS staff(" + + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + + "name VARCHAR(256) NOT NULL," + + "active BOOLEAN NOT NULL DEFAULT true)", + c); + MySqlCommand createMessages = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS messages(" + + "identifier VARCHAR(256) NOT NULL PRIMARY KEY," + + "user_id BIGINT UNSIGNED NOT NULL," + + "message VARCHAR(5000) NOT NULL)", + c); + c.Open(); + createTickets.ExecuteNonQuery(); + createBlacklisted.ExecuteNonQuery(); + createTicketHistory.ExecuteNonQuery(); + createStaffList.ExecuteNonQuery(); + createMessages.ExecuteNonQuery(); + } + } + public static bool IsOpenTicket(ulong channelID) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); + selection.Parameters.AddWithValue("@channel_id", channelID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + return false; + } + results.Close(); + } + return true; + } + public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); + selection.Parameters.AddWithValue("@channel_id", channelID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + ticket = null; + return false; + } + + ticket = new Ticket(results); + results.Close(); + return true; + } + } + public static bool TryGetOpenTicketByID(uint id, out Ticket ticket) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c); + selection.Parameters.AddWithValue("@id", id); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if open ticket exists in the database + if (results.Read()) + { + ticket = new Ticket(results); + return true; + } + + ticket = null; + return false; + } + } + public static bool TryGetClosedTicket(uint id, out Ticket ticket) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c); + selection.Parameters.AddWithValue("@id", id); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if closed ticket exists in the database + if (results.Read()) + { + ticket = new Ticket(results); + return true; + } + + ticket = null; + return false; + } + } + public static bool TryGetOpenTickets(ulong userID, out List tickets) + { + tickets = null; + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c); + selection.Parameters.AddWithValue("@creator_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + } + public static bool TryGetOldestTickets(ulong userID, out List tickets, int listLimit) + { + tickets = null; + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY created_time ASC LIMIT @limit", c); + selection.Parameters.AddWithValue("@creator_id", userID); + selection.Parameters.AddWithValue("@limit", listLimit); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + } + public static bool TryGetClosedTickets(ulong userID, out List tickets) + { + tickets = null; + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c); + selection.Parameters.AddWithValue("@creator_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + } + public static bool TryGetAssignedTickets(ulong staffID, out List tickets) + { + tickets = null; + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c); + selection.Parameters.AddWithValue("@assigned_staff_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + } + public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand cmd = new MySqlCommand( + @"INSERT INTO tickets (created_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", + c); + cmd.Parameters.AddWithValue("@creator_id", memberID); + cmd.Parameters.AddWithValue("@assigned_staff_id", staffID); + cmd.Parameters.AddWithValue("@summary", ""); + cmd.Parameters.AddWithValue("@channel_id", ticketID); + cmd.ExecuteNonQuery(); + return cmd.LastInsertedId; + } + } + + public static void ArchiveTicket(Ticket ticket) + { + // Check if ticket already exists in the archive + if (TryGetClosedTicket(ticket.id, out Ticket _)) + { + using (MySqlConnection c = GetConnection()) + { + MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c); + deleteTicket.Parameters.AddWithValue("@id", ticket.id); + deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); + + c.Open(); + deleteTicket.Prepare(); + deleteTicket.ExecuteNonQuery(); + } + } + + using (MySqlConnection c = GetConnection()) + { + // Create an entry in the ticket history database + MySqlCommand archiveTicket = new MySqlCommand(@"INSERT INTO ticket_history (id, created_time, closed_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (@id, @created_time, UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", c); + archiveTicket.Parameters.AddWithValue("@id", ticket.id); + archiveTicket.Parameters.AddWithValue("@created_time", ticket.createdTime); + archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID); + archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID); + archiveTicket.Parameters.AddWithValue("@summary", ticket.summary); + archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); + + c.Open(); + archiveTicket.Prepare(); + archiveTicket.ExecuteNonQuery(); + } + } + + public static void DeleteOpenTicket(uint ticketID) + { + using (MySqlConnection c = GetConnection()) + { + MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c); + deletion.Parameters.AddWithValue("@id", ticketID); + + c.Open(); + deletion.Prepare(); + deletion.ExecuteNonQuery(); + } + } + + public static bool IsBlacklisted(ulong userID) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if user is blacklisted + if (results.Read()) + { + return true; + } + results.Close(); + } + + return false; + } + public static bool Blacklist(ulong blacklistedID, ulong staffID) + { + using (MySqlConnection c = GetConnection()) + { + try + { + c.Open(); + MySqlCommand cmd = new MySqlCommand(@"INSERT INTO blacklisted_users (user_id,time,moderator_id) VALUES (@user_id, UTC_TIMESTAMP(), @moderator_id);", c); + cmd.Parameters.AddWithValue("@user_id", blacklistedID); + cmd.Parameters.AddWithValue("@moderator_id", staffID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + } + public static bool Unblacklist(ulong blacklistedID) + { + using (MySqlConnection c = GetConnection()) + { + try + { + c.Open(); + MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c); + cmd.Parameters.AddWithValue("@user_id", blacklistedID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + + } + } + public static bool AssignStaff(Ticket ticket, ulong staffID) + { + using (MySqlConnection c = GetConnection()) + { + try + { + c.Open(); + MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET assigned_staff_id = @assigned_staff_id WHERE id = @id", c); + update.Parameters.AddWithValue("@assigned_staff_id", staffID); + update.Parameters.AddWithValue("@id", ticket.id); + update.Prepare(); + return update.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + + } + } + public static bool UnassignStaff(Ticket ticket) + { + return AssignStaff(ticket, 0); + } + public static StaffMember GetRandomActiveStaff(ulong currentStaffID) + { + List staffMembers = GetActiveStaff(currentStaffID); + if (!staffMembers.Any()) + { + return null; + } + + return staffMembers[random.Next(staffMembers.Count)]; + } + + public static List GetActiveStaff(ulong currentStaffID = 0) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true AND user_id != @user_id", c); + selection.Parameters.AddWithValue("@user_id", currentStaffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if staff exists in the database + if (!results.Read()) + { + return new List(); + } + + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) + { + staffMembers.Add(new StaffMember(results)); + } + results.Close(); + + return staffMembers; + } + } + + public static List GetAllStaff(ulong currentStaffID = 0) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id != @user_id", c); + selection.Parameters.AddWithValue("@user_id", currentStaffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if staff exist in the database + if (!results.Read()) + { + return new List(); + } + + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) + { + staffMembers.Add(new StaffMember(results)); + } + results.Close(); + + return staffMembers; + } + } + + public static bool IsStaff(ulong staffID) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + return false; + } + results.Close(); + return true; + } + } + public static bool TryGetStaff(ulong staffID, out StaffMember staffMember) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + staffMember = null; + return false; + } + staffMember = new StaffMember(results); + results.Close(); + return true; + } + } + + public static List GetAllMessages() + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if messages exist in the database + if (!results.Read()) + { + return new List(); + } + + List messages = new List { new Message(results) }; + while (results.Read()) + { + messages.Add(new Message(results)); + } + results.Close(); + + return messages; + } + } + + public static bool TryGetMessage(string identifier, out Message message) + { + using (MySqlConnection c = GetConnection()) + { + c.Open(); + MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c); + selection.Parameters.AddWithValue("@identifier", identifier); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + message = null; + return false; + } + message = new Message(results); + results.Close(); + return true; + } + } + + public static bool AddMessage(string identifier, ulong userID, string message) + { + using (MySqlConnection c = GetConnection()) + { + try + { + c.Open(); + MySqlCommand cmd = new MySqlCommand(@"INSERT INTO messages (identifier,user_id,message) VALUES (@identifier, @user_id, @message);", c); + cmd.Parameters.AddWithValue("@identifier", identifier); + cmd.Parameters.AddWithValue("@user_id", userID); + cmd.Parameters.AddWithValue("@message", message); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + } + + public static bool RemoveMessage(string identifier) + { + using (MySqlConnection c = GetConnection()) + { + try + { + c.Open(); + MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c); + cmd.Parameters.AddWithValue("@identifier", identifier); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + + } + } + + public class Ticket + { + public uint id; + public DateTime createdTime; + public ulong creatorID; + public ulong assignedStaffID; + public string summary; + public ulong channelID; + + public Ticket(MySqlDataReader reader) + { + this.id = reader.GetUInt32("id"); + this.createdTime = reader.GetDateTime("created_time"); + this.creatorID = reader.GetUInt64("creator_id"); + this.assignedStaffID = reader.GetUInt64("assigned_staff_id"); + this.summary = reader.GetString("summary"); + this.channelID = reader.GetUInt64("channel_id"); + } + + public string FormattedCreatedTime() + { + return this.createdTime.ToString(Config.timestampFormat); + } + } + public class StaffMember + { + public ulong userID; + public string name; + public bool active; + + public StaffMember(MySqlDataReader reader) + { + this.userID = reader.GetUInt64("user_id"); + this.name = reader.GetString("name"); + this.active = reader.GetBoolean("active"); + } + } + + public class Message + { + public string identifier; + public ulong userID; + public string message; + + public Message(MySqlDataReader reader) + { + this.identifier = reader.GetString("identifier"); + this.userID = reader.GetUInt64("user_id"); + this.message = reader.GetString("message"); + } + } + } +} \ No newline at end of file diff --git a/SupportChild/EventHandler.cs b/SupportChild/EventHandler.cs new file mode 100644 index 0000000..e9084aa --- /dev/null +++ b/SupportChild/EventHandler.cs @@ -0,0 +1,307 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.CommandsNext.Exceptions; +using DSharpPlus.Entities; +using DSharpPlus.EventArgs; +using DSharpPlus.Exceptions; +using Microsoft.Extensions.Logging; + +namespace SupportChild +{ + internal class EventHandler + { + private DiscordClient discordClient; + + //DateTime for the end of the cooldown + private static Dictionary reactionTicketCooldowns = new Dictionary(); + + public EventHandler(DiscordClient client) + { + this.discordClient = client; + } + + internal Task OnReady(DiscordClient client, ReadyEventArgs e) + { + discordClient.Logger.Log(LogLevel.Information, "Client is ready to process events."); + + // Checking activity type + if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) + { + Console.WriteLine("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); + activityType = ActivityType.Playing; + } + + this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online); + return Task.CompletedTask; + } + + internal Task OnGuildAvailable(DiscordClient client, GuildCreateEventArgs e) + { + discordClient.Logger.Log(LogLevel.Information, $"Guild available: {e.Guild.Name}"); + + IReadOnlyDictionary roles = e.Guild.Roles; + + foreach ((ulong roleID, DiscordRole role) in roles) + { + discordClient.Logger.Log(LogLevel.Information, role.Name.PadRight(40, '.') + roleID); + } + return Task.CompletedTask; + } + + internal Task OnClientError(DiscordClient client, ClientErrorEventArgs e) + { + discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); + + return Task.CompletedTask; + } + + internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) + { + if (e.Author.IsBot) + { + return; + } + + // Check if ticket exists in the database and ticket notifications are enabled + if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications) + { + return; + } + + // Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff + IReadOnlyList messages = await e.Channel.GetMessagesAsync(2); + if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id)) + { + try + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention + }; + + DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID); + await staffMember.SendMessageAsync(message); + } + catch (NotFoundException) { } + catch (UnauthorizedException) { } + } + } + + internal Task OnCommandError(CommandsNextExtension commandSystem, CommandErrorEventArgs e) + { + switch (e.Exception) + { + case CommandNotFoundException _: + return Task.CompletedTask; + case ChecksFailedException _: + { + foreach (CheckBaseAttribute attr in ((ChecksFailedException)e.Exception).FailedChecks) + { + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = this.ParseFailedCheck(attr) + }; + e.Context?.Channel?.SendMessageAsync(error); + } + return Task.CompletedTask; + } + + default: + { + discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); + DiscordEmbed error = new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Internal error occured, please report this to the developer." + }; + e.Context?.Channel?.SendMessageAsync(error); + return Task.CompletedTask; + } + } + } + + internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e) + { + if (e.Message.Id != Config.reactionMessage) return; + + DiscordGuild guild = e.Message.Channel.Guild; + DiscordMember member = await guild.GetMemberAsync(e.User.Id); + + if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id)) return; + if (reactionTicketCooldowns.ContainsKey(member.Id)) + { + if (reactionTicketCooldowns[member.Id] > DateTime.Now) return; // cooldown has not expired + else reactionTicketCooldowns.Remove(member.Id); // cooldown exists but has expired, delete it + } + + + DiscordChannel category = guild.GetChannel(Config.ticketCategory); + DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category); + + if (ticketChannel == null) return; + + ulong staffID = 0; + if (Config.randomAssignment) + { + staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0; + } + + long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id); + reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10)); // add a cooldown which expires in 10 seconds + string ticketID = id.ToString("00000"); + + await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID); + await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None); + await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage); + + // Remove user's reaction + await e.Message.DeleteReactionAsync(e.Emoji, e.User); + + // Refreshes the channel as changes were made to it above + ticketChannel = await SupportChild.GetClient().GetChannelAsync(ticketChannel.Id); + + if (staffID != 0) + { + DiscordEmbed assignmentMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket was randomly assigned to <@" + staffID + ">." + }; + await ticketChannel.SendMessageAsync(assignmentMessage); + + if (Config.assignmentNotifications) + { + DiscordEmbed message = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been randomly assigned to a newly opened support ticket: " + + ticketChannel.Mention + }; + + try + { + DiscordMember staffMember = await guild.GetMemberAsync(staffID); + await staffMember.SendMessageAsync(message); + } + catch (NotFoundException) + { + } + catch (UnauthorizedException) + { + } + } + } + + // Log it if the log channel exists + DiscordChannel logChannel = guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed logMessage = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "Ticket " + ticketID } + }; + await logChannel.SendMessageAsync(logMessage); + } + } + + internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e) + { + if (!Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + { + return; + } + + foreach (Database.Ticket ticket in ownTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None); + DiscordEmbed message = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Green) + .WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."); + await channel.SendMessageAsync(message); + } + } + catch (Exception) { } + } + } + + internal async Task OnMemberRemoved(DiscordClient client, Guild​Member​Remove​Event​Args e) + { + if (Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + { + foreach (Database.Ticket ticket in ownTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + DiscordEmbed message = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."); + await channel.SendMessageAsync(message); + } + } + catch (Exception) { } + } + } + + if (Database.TryGetAssignedTickets(e.Member.Id, out List assignedTickets) && Config.logChannel != 0) + { + DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel); + if (logChannel != null) + { + + foreach (Database.Ticket ticket in assignedTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + DiscordEmbed message = new DiscordEmbedBuilder() + .WithColor(DiscordColor.Red) + .WithDescription("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"); + await logChannel.SendMessageAsync(message); + } + } + catch (Exception) { } + } + } + } + } + + private string ParseFailedCheck(CheckBaseAttribute attr) + { + switch (attr) + { + case CooldownAttribute _: + return "You cannot use do that so often!"; + case RequireOwnerAttribute _: + return "Only the server owner can use that command!"; + case RequirePermissionsAttribute _: + return "You don't have permission to do that!"; + case RequireRolesAttribute _: + return "You do not have a required role!"; + case RequireUserPermissionsAttribute _: + return "You don't have permission to do that!"; + case RequireNsfwAttribute _: + return "This command can only be used in an NSFW channel!"; + default: + return "Unknown Discord API error occured, please try again later."; + } + } + } +} \ No newline at end of file diff --git a/SupportChild/Properties/Resources.Designer.cs b/SupportChild/Properties/Resources.Designer.cs new file mode 100644 index 0000000..4f8fc83 --- /dev/null +++ b/SupportChild/Properties/Resources.Designer.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SupportChild.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SupportChild.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Byte[]. + /// + internal static byte[] default_config { + get { + object obj = ResourceManager.GetObject("default_config", resourceCulture); + return ((byte[])(obj)); + } + } + } +} diff --git a/SupportChild/Properties/Resources.resx b/SupportChild/Properties/Resources.resx new file mode 100644 index 0000000..0e67d79 --- /dev/null +++ b/SupportChild/Properties/Resources.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\default_config.yml;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SupportChild/SupportChild.cs b/SupportChild/SupportChild.cs new file mode 100644 index 0000000..4102e42 --- /dev/null +++ b/SupportChild/SupportChild.cs @@ -0,0 +1,163 @@ +using System; +using System.IO; +using System.Reflection; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.CommandsNext; +using Microsoft.Extensions.Logging; +using SupportChild.Commands; + +namespace SupportChild +{ + internal class SupportChild + { + internal static SupportChild instance; + + private DiscordClient discordClient = null; + private CommandsNextExtension commands = null; + private EventHandler eventHandler; + + static void Main(string[] args) + { + new SupportChild().MainAsync().GetAwaiter().GetResult(); + } + + private async Task MainAsync() + { + instance = this; + + Console.WriteLine("Starting SupportChild version " + GetVersion() + "..."); + try + { + this.Reload(); + + // Block this task until the program is closed. + await Task.Delay(-1); + } + catch (Exception e) + { + Console.WriteLine("Fatal error:"); + Console.WriteLine(e); + Console.ReadLine(); + } + } + + public static DiscordClient GetClient() + { + return instance.discordClient; + } + + public static string GetVersion() + { + Version version = Assembly.GetEntryAssembly()?.GetName().Version; + return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); + } + + public async void Reload() + { + if (this.discordClient != null) + { + await this.discordClient.DisconnectAsync(); + this.discordClient.Dispose(); + Console.WriteLine("Discord client disconnected."); + } + + Console.WriteLine("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\""); + Config.LoadConfig(); + + // Check if token is unset + if (Config.token == "" || Config.token == "") + { + Console.WriteLine("You need to set your bot token in the config and start the bot again."); + throw new ArgumentException("Invalid Discord bot token"); + } + + // Database connection and setup + try + { + Console.WriteLine("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); + Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); + Database.SetupTables(); + } + catch (Exception e) + { + Console.WriteLine("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e); + throw; + } + + Console.WriteLine("Setting up Discord client..."); + + // Checking log level + if (!Enum.TryParse(Config.logLevel, true, out LogLevel logLevel)) + { + Console.WriteLine("Log level '" + Config.logLevel + "' invalid, using 'Information' instead."); + logLevel = LogLevel.Information; + } + + // Setting up client configuration + DiscordConfiguration cfg = new DiscordConfiguration + { + Token = Config.token, + TokenType = TokenType.Bot, + MinimumLogLevel = logLevel, + AutoReconnect = true, + Intents = DiscordIntents.All + }; + + this.discordClient = new DiscordClient(cfg); + + this.eventHandler = new EventHandler(this.discordClient); + + Console.WriteLine("Hooking events..."); + this.discordClient.Ready += this.eventHandler.OnReady; + this.discordClient.GuildAvailable += this.eventHandler.OnGuildAvailable; + this.discordClient.ClientErrored += this.eventHandler.OnClientError; + this.discordClient.MessageCreated += this.eventHandler.OnMessageCreated; + this.discordClient.GuildMemberAdded += this.eventHandler.OnMemberAdded; + this.discordClient.GuildMemberRemoved += this.eventHandler.OnMemberRemoved; + if (Config.reactionMessage != 0) + { + this.discordClient.MessageReactionAdded += this.eventHandler.OnReactionAdded; + } + + Console.WriteLine("Registering commands..."); + commands = discordClient.UseCommandsNext(new CommandsNextConfiguration + { + StringPrefixes = new[] { Config.prefix } + }); + + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + this.commands.RegisterCommands(); + + Console.WriteLine("Hooking command events..."); + this.commands.CommandErrored += this.eventHandler.OnCommandError; + + Console.WriteLine("Connecting to Discord..."); + await this.discordClient.ConnectAsync(); + } + } +} \ No newline at end of file diff --git a/SupportChild/SupportChild.csproj b/SupportChild/SupportChild.csproj new file mode 100644 index 0000000..e53c3e0 --- /dev/null +++ b/SupportChild/SupportChild.csproj @@ -0,0 +1,60 @@ + + + + Exe + net5.0 + 1.1.0 + SupportChild.SupportChild + EmotionChild + + https://github.com/EmotionChild/SupportChild + https://github.com/EmotionChild/SupportChild + Git + LICENSE + + A Discord support bot build for the Ellie's Home Discord server + 2.5.0.0 + 2.5.0.0 + en + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + lib\DiscordChatExporter.Core.dll + + + + diff --git a/SupportChild/Transcriber.cs b/SupportChild/Transcriber.cs new file mode 100644 index 0000000..f0d200f --- /dev/null +++ b/SupportChild/Transcriber.cs @@ -0,0 +1,62 @@ +using System.IO; +using System.Threading.Tasks; + +using DiscordChatExporter.Core.Discord; +using DiscordChatExporter.Core.Discord.Data; +using DiscordChatExporter.Core.Exceptions; +using DiscordChatExporter.Core.Exporting; +using DiscordChatExporter.Core.Exporting.Filtering; +using DiscordChatExporter.Core.Exporting.Partitioning; +using DiscordChatExporter.Core.Utils.Extensions; + +namespace SupportChild +{ + internal static class Transcriber + { + internal static async Task ExecuteAsync(ulong channelID, uint ticketID) + { + DiscordClient discordClient = new DiscordClient(new AuthToken(AuthTokenKind.Bot, Config.token)); + ChannelExporter Exporter = new ChannelExporter(discordClient); + + if (!Directory.Exists("./transcripts")) + { + Directory.CreateDirectory("./transcripts"); + } + + string dateFormat = "yyyy-MMM-dd HH:mm"; + + // Configure settings + if (Config.timestampFormat != "") + dateFormat = Config.timestampFormat; + + Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID)); + Guild guild = await discordClient.GetGuildAsync(channel.GuildId); + + ExportRequest request = new ExportRequest( + guild: guild, + channel: channel, + outputPath: GetPath(ticketID), + format: ExportFormat.HtmlDark, + after: null, + before: null, + partitionLimit: PartitionLimit.Null, + messageFilter: MessageFilter.Null, + shouldDownloadMedia: false, + shouldReuseMedia: false, + dateFormat: dateFormat + ); + + await Exporter.ExportChannelAsync(request); + } + + internal static string GetPath(uint ticketNumber) + { + return "./transcripts/" + GetFilename(ticketNumber); + } + + internal static string GetFilename(uint ticketNumber) + { + return "ticket-" + ticketNumber.ToString("00000") + ".html"; + } + } +} \ No newline at end of file diff --git a/SupportChild/Utilities.cs b/SupportChild/Utilities.cs new file mode 100644 index 0000000..6e56c0b --- /dev/null +++ b/SupportChild/Utilities.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using DSharpPlus.Entities; + +namespace SupportChild +{ + public static class Utilities + { + public static List RandomizeList(List list) + { + RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); + int n = list.Count; + while (n > 1) + { + byte[] box = new byte[1]; + do provider.GetBytes(box); + while (!(box[0] < n * (Byte.MaxValue / n))); + int k = (box[0] % n); + n--; + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + + return list; + } + + public static string[] ParseIDs(string args) + { + if (string.IsNullOrEmpty(args)) + { + return new string[0]; + } + return args.Trim().Replace("<@!", "").Replace("<@", "").Replace(">", "").Split(); + } + + public static LinkedList ParseListIntoMessages(List listItems) + { + LinkedList messages = new LinkedList(); + + foreach (string listItem in listItems) + { + if (messages.Last?.Value?.Length + listItem?.Length < 2048) + { + messages.Last.Value += listItem; + } + else + { + messages.AddLast(listItem); + } + } + + return messages; + } + + public static DiscordRole GetRoleByName(DiscordGuild guild, string Name) + { + Name = Name.Trim().ToLower(); + foreach (DiscordRole role in guild.Roles.Values) + { + if (role.Name.ToLower().StartsWith(Name)) + { + return role; + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/SupportChild/default_config.yml b/SupportChild/default_config.yml new file mode 100644 index 0000000..a68604b --- /dev/null +++ b/SupportChild/default_config.yml @@ -0,0 +1,84 @@ +bot: + # Bot token. + token: "" + # Command prefix. + prefix: "+" + # Channel where ticket logs are posted (recommended) + log-channel: 000000000000000000 + # Category where the ticket will be created, it will have the same permissions of that ticket plus read permissions for the user opening the ticket (recommended) + ticket-category: 000000000000000000 + # A message which will open new tickets when users react to it (optional) + reaction-message: 000000000000000000 + # Message posted when a ticket is opened. + welcome-message: "Please describe your issue below, and include all information needed for us to help you." + # Decides what messages are shown in console + # Possible values are: Critical, Error, Warning, Information, Debug. + console-log-level: "Information" + # Format for timestamps in transcripts and google sheets if used + timestamp-format: "yyyy-MM-dd HH:mm" + # Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command. + random-assignment: true + # If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command. + # This can be useful if you have admins set as inactive to not automatically recieve tickets and then have moderators elevate tickets when needed. + random-assign-role-override: true + # Sets the type of activity for the bot to display in its presence status + # Possible values are: Playing, Streaming, ListeningTo, Watching, Competing + presence-type: "ListeningTo" + # Sets the activity text shown in the bot's status + presence-text: "+new" + +notifications: + # Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time + # Other staff members and bots do not trigger this. + ticket-updated: true + # The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days. + ticket-updated-delay: 0.5 + # Notifies staff when they are assigned to tickets + assignment: true + # Notifies the user opening the ticket that their ticket was closed and includes the transcript + closing: true + +database: + # Address and port of the mysql server + address: "127.0.0.1" + port: 3306 + # Name of the database to use + name: "supportbot" + # Username and password for authentication + user: "" + password: "" + +# Set up which roles are allowed to use different commands. +# Example: +# new: [ 000000000000000000, 111111111111111111 ] +# They are grouped into suggested command groups below for first time setup. +permissions: + # Public commands + close: [] + list: [] + new: [] + say: [] + status: [] + summary: [] + transcript: [] + # Moderator commands + add: [] + addmessage: [] + assign: [] + blacklist: [] + listassigned: [] + listoldest: [] + listunassigned: [] + move: [] + rassign: [] + removemessage: [] + setsummary: [] + toggleactive: [] + unassign: [] + unblacklist: [] + # Admin commands + addstaff: [] + reload: [] + removestaff: [] + setticket: [] + unsetticket: [] \ No newline at end of file diff --git a/SupportChild/lib/DiscordChatExporter.Core.dll b/SupportChild/lib/DiscordChatExporter.Core.dll new file mode 100644 index 0000000..e27417e Binary files /dev/null and b/SupportChild/lib/DiscordChatExporter.Core.dll differ diff --git a/SupportChild/warp-packer.exe b/SupportChild/warp-packer.exe new file mode 100644 index 0000000..0d74095 Binary files /dev/null and b/SupportChild/warp-packer.exe differ