Compare commits

...

No commits in common. "v6" and "2.44.2" have entirely different histories.
v6 ... 2.44.2

1979 changed files with 311103 additions and 156499 deletions

View File

@ -1,14 +0,0 @@
# Ignore all files
*
# Don't ignore nugetconfig
!./NuGet.Config
# Don't ignore src projects
!src/**
!docker-entrypoint.sh
# ignore bin and obj folders in projects
src/**/bin/*
src/**/obj/*
src/NadekoBot/data/creds.yml

View File

@ -1,208 +0,0 @@
[*]
charset = utf-8-bom
end_of_line = crlf
trim_trailing_whitespace = false
insert_final_newline = false
indent_style = space
indent_size = 4
# Microsoft .NET properties
csharp_new_line_before_members_in_object_initializers = false
csharp_preferred_modifier_order = public, private, protected, internal, file, new, static, abstract, virtual, sealed, readonly, override, extern, unsafe, volatile, async, required:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
dotnet_naming_rule.constants_rule.import_to_resharper = True
dotnet_naming_rule.constants_rule.resharper_description = Constant fields (not private)
dotnet_naming_rule.constants_rule.resharper_guid = 669e5282-fb4b-4e90-91e7-07d269d04b60
dotnet_naming_rule.constants_rule.severity = suggestion
dotnet_naming_rule.constants_rule.style = all_upper_style
dotnet_naming_rule.constants_rule.symbols = constants_symbols
dotnet_naming_rule.interfaces_rule.import_to_resharper = True
dotnet_naming_rule.interfaces_rule.resharper_description = Interfaces
dotnet_naming_rule.interfaces_rule.resharper_guid = a7a3339e-4e89-4319-9735-a9dc4cb74cc7
dotnet_naming_rule.interfaces_rule.severity = suggestion
dotnet_naming_rule.interfaces_rule.style = i_upper_camel_case_style
dotnet_naming_rule.interfaces_rule.symbols = interfaces_symbols
dotnet_naming_rule.local_constants_rule.import_to_resharper = True
dotnet_naming_rule.local_constants_rule.resharper_description = Local constants
dotnet_naming_rule.local_constants_rule.resharper_guid = a4f433b8-abcd-4e55-a08f-82e78cef0f0c
dotnet_naming_rule.local_constants_rule.severity = suggestion
dotnet_naming_rule.local_constants_rule.style = all_upper_style
dotnet_naming_rule.local_constants_rule.symbols = local_constants_symbols
dotnet_naming_rule.private_constants_rule.import_to_resharper = True
dotnet_naming_rule.private_constants_rule.resharper_description = Constant fields (private)
dotnet_naming_rule.private_constants_rule.resharper_guid = 236f7aa5-7b06-43ca-bf2a-9b31bfcff09a
dotnet_naming_rule.private_constants_rule.severity = suggestion
dotnet_naming_rule.private_constants_rule.style = all_upper_style
dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols
dotnet_naming_rule.private_instance_fields_rule.import_to_resharper = True
dotnet_naming_rule.private_instance_fields_rule.resharper_description = Instance fields (private)
dotnet_naming_rule.private_instance_fields_rule.resharper_guid = 4a98fdf6-7d98-4f5a-afeb-ea44ad98c70c
dotnet_naming_rule.private_instance_fields_rule.severity = suggestion
dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style
dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols
dotnet_naming_rule.private_static_fields_rule.import_to_resharper = True
dotnet_naming_rule.private_static_fields_rule.resharper_description = Static fields (private)
dotnet_naming_rule.private_static_fields_rule.resharper_exclusive_prefixes_suffixes = true
dotnet_naming_rule.private_static_fields_rule.resharper_guid = f9fce829-e6f4-4cb2-80f1-5497c44f51df
dotnet_naming_rule.private_static_fields_rule.severity = suggestion
dotnet_naming_rule.private_static_fields_rule.style = lower_camel_case_style
dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols
dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = True
dotnet_naming_rule.private_static_readonly_rule.resharper_description = Static readonly fields (private)
dotnet_naming_rule.private_static_readonly_rule.resharper_guid = 15b5b1f1-457c-4ca6-b278-5615aedc07d3
dotnet_naming_rule.private_static_readonly_rule.severity = suggestion
dotnet_naming_rule.private_static_readonly_rule.style = lower_camel_case_style
dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols
dotnet_naming_rule.type_parameters_rule.import_to_resharper = True
dotnet_naming_rule.type_parameters_rule.resharper_description = Type parameters
dotnet_naming_rule.type_parameters_rule.resharper_guid = 2c62818f-621b-4425-adc9-78611099bfcb
dotnet_naming_rule.type_parameters_rule.severity = suggestion
dotnet_naming_rule.type_parameters_rule.style = t_upper_camel_case_style
dotnet_naming_rule.type_parameters_rule.symbols = type_parameters_symbols
dotnet_naming_style.all_upper_style.capitalization = all_upper
dotnet_naming_style.all_upper_style.word_separator = _
dotnet_naming_style.i_upper_camel_case_style.capitalization = pascal_case
dotnet_naming_style.i_upper_camel_case_style.required_prefix = I
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_style.lower_camel_case_style.required_prefix = _
dotnet_naming_style.t_upper_camel_case_style.capitalization = pascal_case
dotnet_naming_style.t_upper_camel_case_style.required_prefix = T
dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public,internal,protected,protected_internal,private_protected
dotnet_naming_symbols.constants_symbols.applicable_kinds = field
dotnet_naming_symbols.constants_symbols.required_modifiers = const
dotnet_naming_symbols.constants_symbols.resharper_applicable_kinds = constant_field
dotnet_naming_symbols.constants_symbols.resharper_required_modifiers = any
dotnet_naming_symbols.interfaces_symbols.applicable_accessibilities = *
dotnet_naming_symbols.interfaces_symbols.applicable_kinds = interface
dotnet_naming_symbols.interfaces_symbols.resharper_applicable_kinds = interface
dotnet_naming_symbols.interfaces_symbols.resharper_required_modifiers = any
dotnet_naming_symbols.local_constants_symbols.applicable_accessibilities = *
dotnet_naming_symbols.local_constants_symbols.applicable_kinds = local
dotnet_naming_symbols.local_constants_symbols.required_modifiers = const
dotnet_naming_symbols.local_constants_symbols.resharper_applicable_kinds = local_constant
dotnet_naming_symbols.local_constants_symbols.resharper_required_modifiers = any
dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field
dotnet_naming_symbols.private_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_constants_symbols.resharper_applicable_kinds = constant_field
dotnet_naming_symbols.private_constants_symbols.resharper_required_modifiers = any
dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_instance_fields_symbols.resharper_applicable_kinds = field,readonly_field
dotnet_naming_symbols.private_instance_fields_symbols.resharper_required_modifiers = instance
dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static
dotnet_naming_symbols.private_static_fields_symbols.resharper_applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.resharper_required_modifiers = static
dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = readonly,static
dotnet_naming_symbols.private_static_readonly_symbols.resharper_applicable_kinds = readonly_field
dotnet_naming_symbols.private_static_readonly_symbols.resharper_required_modifiers = static
dotnet_naming_symbols.type_parameters_symbols.applicable_accessibilities = *
dotnet_naming_symbols.type_parameters_symbols.applicable_kinds = type_parameter
dotnet_naming_symbols.type_parameters_symbols.resharper_applicable_kinds = type_parameter
dotnet_naming_symbols.type_parameters_symbols.resharper_required_modifiers = any
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_qualification_for_event = false:suggestion
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
# ReSharper properties
resharper_autodetect_indent_settings = true
resharper_csharp_wrap_arguments_style = chop_if_long
resharper_force_attribute_style = join
resharper_formatter_off_tag = @formatter:off
resharper_formatter_on_tag = @formatter:on
resharper_formatter_tags_enabled = true
resharper_keep_existing_embedded_arrangement = false
resharper_keep_existing_expr_member_arrangement = false
resharper_method_or_operator_body = expression_body
resharper_object_creation_when_type_not_evident = target_typed
resharper_place_accessorholder_attribute_on_same_line = false
resharper_place_accessor_attribute_on_same_line = false
resharper_place_expr_method_on_single_line = false
resharper_place_expr_property_on_single_line = false
resharper_place_field_attribute_on_same_line = false
resharper_place_simple_embedded_statement_on_same_line = false
resharper_show_autodetect_configure_formatting_tip = false
resharper_use_indent_from_vs = false
resharper_wrap_before_arrow_with_expressions = true
# ReSharper inspection severities
resharper_arrange_constructor_or_destructor_body_highlighting = hint
resharper_arrange_method_or_operator_body_highlighting = suggestion
resharper_arrange_object_creation_when_type_evident_highlighting = none
resharper_arrange_redundant_parentheses_highlighting = suggestion
resharper_arrange_this_qualifier_highlighting = hint
resharper_arrange_type_member_modifiers_highlighting = none
resharper_built_in_type_reference_style_for_member_access_highlighting = hint
resharper_built_in_type_reference_style_highlighting = hint
resharper_check_namespace_highlighting = none
resharper_class_never_instantiated_global_highlighting = hint
resharper_convert_to_primary_constructor_highlighting = none
resharper_convert_to_using_declaration_highlighting = warning
resharper_convert_type_check_pattern_to_null_check_highlighting = hint
resharper_empty_general_catch_clause_highlighting = none
resharper_function_never_returns_highlighting = suggestion
resharper_inconsistent_naming_highlighting = suggestion
resharper_invert_if_highlighting = none
resharper_lambda_expression_can_be_made_static_highlighting = hint
resharper_mvc_action_not_resolved_highlighting = warning
resharper_mvc_area_not_resolved_highlighting = warning
resharper_mvc_controller_not_resolved_highlighting = warning
resharper_mvc_masterpage_not_resolved_highlighting = warning
resharper_mvc_partial_view_not_resolved_highlighting = warning
resharper_mvc_template_not_resolved_highlighting = warning
resharper_mvc_view_component_not_resolved_highlighting = warning
resharper_mvc_view_component_view_not_resolved_highlighting = warning
resharper_mvc_view_not_resolved_highlighting = warning
resharper_non_readonly_member_in_get_hash_code_highlighting = suggestion
resharper_not_accessed_field_local_highlighting = suggestion
resharper_out_parameter_value_is_always_discarded_local_highlighting = suggestion
resharper_private_field_can_be_converted_to_local_variable_highlighting = suggestion
resharper_razor_assembly_not_resolved_highlighting = warning
resharper_redundant_anonymous_type_property_name_highlighting = suggestion
resharper_redundant_base_qualifier_highlighting = warning
resharper_redundant_pattern_parentheses_highlighting = none
resharper_redundant_record_class_keyword_highlighting = suggestion
resharper_replace_with_single_call_to_first_or_default_highlighting = hint
resharper_suggest_var_or_type_built_in_types_highlighting = hint
resharper_suggest_var_or_type_elsewhere_highlighting = hint
resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_unused_method_return_value_local_highlighting = suggestion
resharper_use_await_using_highlighting = warning
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
[{*.har,*.json,*.jsonc,*.postman_collection,*.postman_collection.json,*.postman_environment,*.postman_environment.json}]
indent_style = space
indent_size = 2
[{*.yaml,*.yml}]
indent_style = space
indent_size = 2
[{*.bash,*.sh,*.zsh}]
indent_style = space
indent_size = 2
[*.proto]
indent_style = space
indent_size = 2
[*.{appxmanifest,asax,ascx,aspx,axaml,blockshader,build,cg,cginc,compute,cs,cshtml,dtd,fx,fxh,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,shaderFoundry,skin,urtshader,usf,ush,vb,xaml,xamlx,xoml,xsd}]
indent_style = space
indent_size = 4
tab_width = 4

5
.gitbook.yaml Normal file
View File

@ -0,0 +1,5 @@
root: ./
structure:
readme: docs/index.md
summary: SUMMARY.md

View File

@ -1,171 +0,0 @@
name: CI/CD
on:
push:
branches: [ v6 ]
tags:
- '*'
pull_request:
branches: [ v6 ]
env:
DOTNET_VERSION: '8.0.x'
REGISTRY: ghcr.io
jobs:
test:
name: Run Tests
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Restore dependencies
run: dotnet restore
- name: Test
run: dotnet test -c Release --verbosity normal
build:
name: Build Package
needs: test
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
strategy:
matrix:
runtime: [linux-x64, linux-arm64, win-x64, win-arm64, osx-x64, osx-arm64]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Publish
run: |
dotnet publish -c Release -r ${{ matrix.runtime }} \
--self-contained \
-p:Version=${{ github.ref_name }} \
-o wiz-${{ matrix.runtime }} src/WizBot/WizBot.csproj
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: wiz-${{ matrix.runtime }}
path: wiz-${{ matrix.runtime }}
create-release:
name: Create Release
needs:
- build
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
pattern: 'wiz-*'
path: artifacts
- name: Create archives
run: |
cd artifacts
for dir in */; do
runtime="${dir%/}"
if [[ "$runtime" == *"win"* ]]; then
zip -r "$runtime.zip" "$runtime"
else
chmod +x "$runtime/WizBot"
tar -czf "$runtime.tar.gz" "$runtime"
fi
done
- name: Create Release
id: create_release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: Release ${{ github.ref_name }}
body: |
[Changelog](https://github.com/Wizkiller96/WizBot/blob/v6/CHANGELOG.md)
generate_release_notes: true
draft: false
prerelease: false
files: |
artifacts/*.zip
artifacts/*.tar.gz
docker:
name: Build and Push Docker image
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
needs: build
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log into registry ${{ env.REGISTRY }}
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
push: true
context: .
tags: ghcr.io/wizkiller96/wizbot:latest,ghcr.io/wizkiller96/wizbot:v6,ghcr.io/wizkiller96/wizbot:${{ github.ref_name }}
publish-medusa-package:
name: Publish Medusa Package
needs: build
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: Set version
run: |
if [[ $GITHUB_REF == refs/tags/* ]]; then
echo "MEDUSA_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
else
LAST_TAG=$(git describe --tags --abbrev=0)
echo "MEDUSA_VERSION=${LAST_TAG}-alpha${GITHUB_SHA::7}" >> $GITHUB_ENV
fi
- name: Pack and Push
working-directory: src/Wiz.Medusa
run: |
dotnet pack -c Release /p:Version=${{ env.MEDUSA_VERSION }} -o bin/Release/packed
dotnet nuget push bin/Release/packed/*.nupkg --source https://www.myget.org/F/wizbot/api/v2/package --api-key ${{ secrets.MYGET_API_KEY }}
continue-on-error: true

View File

@ -1,36 +0,0 @@
name: Deploy WizBot Docs
on:
push:
branches: ["v6"]
paths:
- 'docs/**'
workflow_dispatch:
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: 'pip'
cache-dependency-path: 'docs/mkdocs-requirements.txt'
- name: Install project dependencies
run: pip install -r docs/mkdocs-requirements.txt
- name: Build the site with MkDocs
working-directory: ./docs
run: mkdocs build --strict
- name: Deploy to GitHub Pages
working-directory: ./docs
run: mkdocs gh-deploy --force

742
.gitignore vendored
View File

@ -1,376 +1,366 @@
#Manually added files
src/WizBot/data/last_known_version.txt
# medusa stuff
src/WizBot/data/medusae/
# other
output/
src/WizBot/output
src/WizBot/creds.yml
src/WizBot/data/creds.yml
src/WizBot/Command Errors*.txt
src/WizBot/data/WizBot.db*
# Created by https://www.gitignore.io/api/visualstudio,visualstudiocode,windows,linux,macos
### VisualStudioCode ###
.vscode/
.vscode/*
# !.vscode/settings.json
# !.vscode/tasks.json
# !.vscode/launch.json
### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# 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
# TODO: 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
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v4's project.json files produces more ignoreable 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
# 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
node_modules/
orleans.codegen.cs
# 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
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/
### VisualStudio Patch ###
build/
site/
## AI
.aider.*
PROMPT.md
.*rules
## Python pip/env files
Pipfile
Pipfile.lock
.venv
#Manually added files
patreon_rewards.json
command_errors*.txt
_output/
src/WizBot/Command Errors*.txt
src/WizBot/credentials.json
# these 2 are used for migrations
WizBot.Core/credentials.json
WizBot.Core/credentials_example.json
src/WizBot/data/WizBot.db
src/WizBot/data/musicdata
# Created by https://www.gitignore.io/api/visualstudio,visualstudiocode,windows,linux,macos
### VisualStudioCode ###
.vscode/
.vscode/*
# !.vscode/settings.json
# !.vscode/tasks.json
# !.vscode/launch.json
### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# 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
# TODO: 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
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable 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
# 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
node_modules/
orleans.codegen.cs
# 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
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/
### VisualStudio Patch ###
build/
site/
src/WizBot/credentials.json

19
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,19 @@
# taken from https://gitlab.com/forrestab/dotnet-gitlab-ci/blob/master/.gitlab-ci.yml
image: mcr.microsoft.com/dotnet/core/sdk:3.1
stages:
- build
variables:
project: "WizBot"
before_script:
- "dotnet restore"
build:
stage: build
variables:
build_path: "src/$project"
script:
- "cd $build_path"
- "dotnet build -c Release"

2
.travis.yml Normal file
View File

@ -0,0 +1,2 @@
language: csharp
solution: WizBot.sln

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /source
# Copy the .csproj files for each project
COPY src/Wiz.Medusa/*.csproj src/Wiz.Medusa/
COPY src/WizBot/*.csproj src/WizBot/
COPY src/WizBot.Coordinator/*.csproj src/WizBot.Coordinator/
COPY src/WizBot.Generators/*.csproj src/WizBot.Generators/
COPY src/WizBot.Voice/*.csproj src/WizBot.Voice/
COPY src/WizBot.GrpcApiBase/*.csproj src/WizBot.GrpcApiBase/
# Restore the dependencies for the WizBot project
RUN dotnet restore src/WizBot/ -r linux-musl-x64
# Copy the rest of the source code
COPY . .
WORKDIR /source/src/WizBot
# Build for linux-musl-x64 runtime as the image is based on alpine
RUN dotnet publish -c Release -o /app --self-contained -r linux-musl-x64 --no-restore \
&& mv /app/data /app/data_init \
&& chmod +x /app/WizBot
# Final stage
FROM alpine:3.20
WORKDIR /app
# Music dependencies
ADD --chmod=755 https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux /usr/local/bin/yt-dlp
RUN apk add --no-cache ffmpeg libsodium
# Required dependencies
# icu-libs is required for globalization
RUN apk update; \
apk add --no-cache libstdc++ libgcc icu-libs libc6-compat \
&& rm -rf /var/cache/apk/*;
COPY --from=build /app ./
COPY docker-entrypoint.sh /usr/local/sbin/
RUN rm /app/data_init/lib/libsodium.so \
&& ln -s /usr/lib/libsodium.so.26 /app/data_init/lib/libsodium.so
VOLUME [ "/app/data" ]
ENTRYPOINT [ "/usr/local/sbin/docker-entrypoint.sh" ]
CMD [ "./WizBot" ]

View File

@ -1,619 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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

View File

@ -1,16 +0,0 @@
Copyright (C) 2025 NadekoBot
- This program is dual licensed under AGPLv3 and Commercial license.
- You may purchase a commercial license to exempt yourself from some of the AGPLv3 obligations
If you're looking for a commercial license, please reach out to me.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Contact: br.eaker on Discord or nadekodiscordbot@gmail.com

8
NuGet.Config Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="Discord.Net" value="https://www.myget.org/F/discord-net/api/v3/index.json" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="Kwoth-myget" value="https://www.myget.org/F/kwoth/api/v3/index.json" />
</packageSources>
</configuration>

View File

@ -1,50 +1,11 @@
# WizBot
[![CI/CD](https://github.com/Wizkiller96/WizBot/actions/workflows/ci.yml/badge.svg)](https://github.com/Wizkiller96/WizBot/actions/workflows/ci.yml)
## Repo Status
WizBot is an open source Discord bot. It is written in C# and is built on .NET 8.
![img](https://ci.appveyor.com/api/projects/status/uuewoyb3t5f7ye4q?svg=true) [![pipeline status](https://gitlab.com/WizNet/WizBot/badges/1.9/pipeline.svg)](https://gitlab.com/WizNet/WizBot/commits/1.9) [![Documentation Status](https://readthedocs.org/projects/wizbot/badge/?version=latest)](http://wizbot.readthedocs.io/en/latest/?badge=latest) [![CodeFactor](https://www.codefactor.io/repository/github/wizkiller96/wizbot/badge)](https://www.codefactor.io/repository/github/wizkiller96/wizbot) ![WizBot Website](https://img.shields.io/website-up-down-green-red/https/wizbot.cc.svg?label=wizbot.cc) [![Discord](https://discordapp.com/api/guilds/99273784988557312/widget.png)](https://discord.gg/0YNaDOYuD5QOpeNI)
If you want to run your own instance of WizBot, please check out the [Self hosting Guides and Docs](https://docs.wizbot.cc).
## For Updates, Help and Guidelines
If you have any questions, please visit our [Discord support server](https://wizbot.cc/discord).
## Installation
### Default option
You may want to consider using [WizBot Updater](https://github.com/Wizkiller96/wizbot-updater/releases) if you want to run bot on your PC.+
### Hosting on a linux server
If you want your bot to be online 24/7, you should [host it on a linux vps](https://docs.wizbot.cc/guides/linux-guide).
### Docker
There is an official Docker image for a [simple setup](https://docs.wizbot.cc/guides/docker-guide/)
Short version:
```sh
docker run -d --name wizbot ghcr.io/wizkiller96/wizbot:v6 -e bot_token=YOUR_TOKEN_HERE -v "./data:/app/data" && docker logs -f --tail 500 wizbot
```
## Contributing to WizBot
We love your input! We want to make contributing to this project as easy as possible, whether it's:
- Reporting a bug
- Discussing the current state of the code
- Submitting a fix
- Proposing new features
- Becoming a maintainer
### Contribution
By submitting code, content, or materials via pull request or similar means ("Contribution"), you irrevocably assign all
intellectual property rights (including copyright and patents) to WizBot Repository Owner and affirm you either:
- (a) own the Contribution outright, or
- (b) it is licensed under compatible terms permitting unrestricted relicensing.
You grant the WizBot Repository Owner perpetual, worldwide rights to use, modify, distribute, and sublicense the
Contribution under AGPLv3, a commercial license, or any other terms without compensation.
These terms survive termination of this agreement.
| [![twitter](https://cdn.discordapp.com/attachments/155726317222887425/252192520094613504/twiter_banner.JPG)](https://twitter.com/WizBot_Dev) | [![Wiki](https://cdn.discordapp.com/attachments/266240393639755778/281920793330581506/datcord.png)](http://wizbot.readthedocs.io/en/latest/) |
| :--- | :--- |
| **Follow me on Twitter.** | **Read the Docs for self-hosting.** |

32
SUMMARY.md Normal file
View File

@ -0,0 +1,32 @@
# Table of contents
* [About](docs/about.md)
## Guides
* [Setting up WizBot on Docker](docs/guides/docker-guide-legacy.md)
* [Setting up WizBot on Docker](docs/guides/docker-guide.md)
* [Setting up WizBot From Source](docs/guides/from-source.md)
* [Setting up WizBot on Linux](docs/guides/linux-guide.md)
* [Setting Up WizBot on OSX \(macOS\)](docs/guides/osx-guide.md)
* [Setting Up WizBot on Windows With the Updater](docs/guides/windows-guide.md)
## Commands
* [Readme](docs/readme.md)
* [Commands List](docs/commands-list.md)
## Features Explained
* [JSON Explanations](docs/json-explanations.md)
* [Permissions Overview](docs/permissions-system.md)
* [Custom Reactions](docs/custom-reactions.md)
* [Placeholders](docs/placeholders.md)
* [Frequently Asked Questions](docs/frequently-asked-questions.md)
* [Bot Config](docs/bce-guide.md)
## Other
* [Frequently Asked Questions](docs/frequently-asked-questions.md)
* [Contribution Guide](docs/contribution-guide.md)
* [❤ Donate ❤](docs/donate.md)

View File

@ -0,0 +1,20 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace WizBot.Common
{
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Run(valueFactory))
{ }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Run(taskFactory))
{ }
public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using WizBot.Core.Services;
using Microsoft.Extensions.DependencyInjection;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class AdminOnlyAttribute : PreconditionAttribute
{
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo executingCommand, IServiceProvider services)
{
var creds = services.GetService<IBotCredentials>();
return Task.FromResult((creds.IsOwner(context.User) || creds.IsAdmin(context.User) || context.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not bot owner or bot admin")));
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Discord.Commands;
using WizBot.Core.Services.Impl;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class AliasesAttribute : AliasAttribute
{
public AliasesAttribute([CallerMemberName] string memberName = "")
: base(CommandNameLoadHelper.GetAliasesFor(memberName))
{
}
}
}

View File

@ -0,0 +1,15 @@
using Discord.Commands;
namespace Discord
{
public class BotPermAttribute : RequireBotPermissionAttribute
{
public BotPermAttribute(GuildPerm permission) : base((GuildPermission)permission)
{
}
public BotPermAttribute(ChannelPerm permission) : base((ChannelPermission)permission)
{
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace WizBot.Common.Attributes
{
public static class CommandNameLoadHelper
{
private static YamlDotNet.Serialization.IDeserializer _deserializer
= new YamlDotNet.Serialization.Deserializer();
public static Lazy<Dictionary<string, string[]>> LazyCommandAliases
= new Lazy<Dictionary<string, string[]>>(() => LoadCommandNames());
public static Dictionary<string, string[]> LoadCommandNames(string aliasesFilePath = "data/aliases.yml")
{
var text = File.ReadAllText(aliasesFilePath);
return _deserializer.Deserialize<Dictionary<string, string[]>>(text);
}
public static string[] GetAliasesFor(string methodName)
=> LazyCommandAliases.Value.TryGetValue(methodName.ToLowerInvariant(), out var aliases) && aliases.Length > 1
? aliases.Skip(1).ToArray()
: Array.Empty<string>();
public static string GetCommandNameFor(string methodName)
{
methodName = methodName.ToLowerInvariant();
var toReturn = LazyCommandAliases.Value.TryGetValue(methodName, out var aliases) && aliases.Length > 0
? aliases[0]
: methodName;
return toReturn;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Runtime.CompilerServices;
using Discord.Commands;
using WizBot.Core.Services.Impl;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class DescriptionAttribute : SummaryAttribute
{
// Localization.LoadCommand(memberName.ToLowerInvariant()).Desc
public DescriptionAttribute(string text = "") : base(text)
{
}
}
}

View File

@ -0,0 +1,9 @@
namespace Discord.Commands
{
public class LeftoverAttribute : RemainderAttribute
{
public LeftoverAttribute()
{
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using WizBot.Core.Services;
using Microsoft.Extensions.DependencyInjection;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class OwnerOnlyAttribute : PreconditionAttribute
{
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo executingCommand, IServiceProvider services)
{
var creds = services.GetService<IBotCredentials>();
return Task.FromResult((creds.IsOwner(context.User) || context.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not bot owner")));
}
}
}

View File

@ -0,0 +1,38 @@
using Discord.Commands;
using WizBot.Core.Services;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace WizBot.Core.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class RatelimitAttribute : PreconditionAttribute
{
public int Seconds { get; }
public RatelimitAttribute(int seconds)
{
if (seconds <= 0)
throw new ArgumentOutOfRangeException(nameof(seconds));
Seconds = seconds;
}
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
if (Seconds == 0)
return Task.FromResult(PreconditionResult.FromSuccess());
var cache = services.GetService<IDataCache>();
var rem = cache.TryAddRatelimit(context.User.Id, command.Name, Seconds);
if(rem == null)
return Task.FromResult(PreconditionResult.FromSuccess());
var msgContent = $"You can use this command again in {rem.Value.TotalSeconds:F1}s.";
return Task.FromResult(PreconditionResult.FromError(msgContent));
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Runtime.CompilerServices;
using Discord.Commands;
using WizBot.Core.Services.Impl;
using Newtonsoft.Json;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class UsageAttribute : RemarksAttribute
{
// public static string GetUsage(string memberName)
// {
// var usage = Localization.LoadCommand(memberName.ToLowerInvariant()).Usage;
// return JsonConvert.SerializeObject(usage);
// }
public UsageAttribute(string text = "") : base(text)
{
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using WizBot.Modules.Administration.Services;
namespace Discord
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class UserPermAttribute : PreconditionAttribute
{
public RequireUserPermissionAttribute UserPermissionAttribute { get; }
public UserPermAttribute(GuildPerm permission)
{
UserPermissionAttribute = new RequireUserPermissionAttribute((GuildPermission)permission);
}
public UserPermAttribute(ChannelPerm permission)
{
UserPermissionAttribute = new RequireUserPermissionAttribute((ChannelPermission)permission);
}
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
var permService = services.GetService<DiscordPermOverrideService>();
if (permService.TryGetOverrides(context.Guild?.Id ?? 0, command.Name.ToUpperInvariant(), out var _))
return Task.FromResult(PreconditionResult.FromSuccess());
return UserPermissionAttribute.CheckPermissionsAsync(context, command, services);
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Runtime.CompilerServices;
using Discord.Commands;
using WizBot.Core.Services.Impl;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class WizBotCommandAttribute : CommandAttribute
{
public WizBotCommandAttribute([CallerMemberName] string memberName = "")
: base(CommandNameLoadHelper.GetCommandNameFor(memberName))
{
this.MethodName = memberName.ToLowerInvariant();
}
public string MethodName { get; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using Discord.Commands;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Class)]
sealed class WizBotModuleAttribute : GroupAttribute
{
public WizBotModuleAttribute(string moduleName) : base(moduleName)
{
}
}
}

View File

@ -0,0 +1,15 @@
using System;
namespace WizBot.Common.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class WizBotOptionsAttribute : Attribute
{
public Type OptionType { get; set; }
public WizBotOptionsAttribute(Type t)
{
this.OptionType = t;
}
}
}

View File

@ -0,0 +1,26 @@
namespace WizBot.Common
{
public enum BotConfigEditType
{
/// <summary>
/// The amount of currency awarded to the winner of the trivia game.
/// Default is 0.
/// </summary>
TriviaCurrencyReward,
/// <summary>
/// Users can't start trivia games which have smaller win requirement than specified by this setting.
/// Default is 0.
/// </summary>
MinimumTriviaWinReq,
/// <summary>
/// The amount of XP the user receives when they send a message (which is not too short).
/// Default is 3.
/// </summary>
XpPerMessage,
/// <summary>
/// This value represents how often the user can receive XP from sending messages.
/// Default is 5.
/// </summary>
XpMinutesTimeout,
}
}

View File

@ -0,0 +1,126 @@
using Discord;
using WizBot.Extensions;
using Newtonsoft.Json;
using System;
namespace WizBot.Common
{
public class CREmbed
{
public CREmbedAuthor Author { get; set; }
public string PlainText { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public CREmbedFooter Footer { get; set; }
public string Thumbnail { get; set; }
public string Image { get; set; }
public CREmbedField[] Fields { get; set; }
public uint Color { get; set; } = 7458112;
public bool IsValid =>
IsEmbedValid || !string.IsNullOrWhiteSpace(PlainText);
public bool IsEmbedValid =>
!string.IsNullOrWhiteSpace(Title) ||
!string.IsNullOrWhiteSpace(Description) ||
!string.IsNullOrWhiteSpace(Url) ||
!string.IsNullOrWhiteSpace(Thumbnail) ||
!string.IsNullOrWhiteSpace(Image) ||
(Footer != null && (!string.IsNullOrWhiteSpace(Footer.Text) || !string.IsNullOrWhiteSpace(Footer.IconUrl))) ||
(Fields != null && Fields.Length > 0);
public EmbedBuilder ToEmbed()
{
var embed = new EmbedBuilder();
if (!string.IsNullOrWhiteSpace(Title))
embed.WithTitle(Title);
if (!string.IsNullOrWhiteSpace(Description))
embed.WithDescription(Description);
if (Url != null && Uri.IsWellFormedUriString(Url, UriKind.Absolute))
embed.WithUrl(Url);
embed.WithColor(new Discord.Color(Color));
if (Footer != null)
embed.WithFooter(efb =>
{
efb.WithText(Footer.Text);
if (Uri.IsWellFormedUriString(Footer.IconUrl, UriKind.Absolute))
efb.WithIconUrl(Footer.IconUrl);
});
if (Thumbnail != null && Uri.IsWellFormedUriString(Thumbnail, UriKind.Absolute))
embed.WithThumbnailUrl(Thumbnail);
if (Image != null && Uri.IsWellFormedUriString(Image, UriKind.Absolute))
embed.WithImageUrl(Image);
if (Author != null && !string.IsNullOrWhiteSpace(Author.Name))
{
if (!Uri.IsWellFormedUriString(Author.IconUrl, UriKind.Absolute))
Author.IconUrl = null;
if (!Uri.IsWellFormedUriString(Author.Url, UriKind.Absolute))
Author.Url = null;
embed.WithAuthor(Author.Name, Author.IconUrl, Author.Url);
}
if (Fields != null)
foreach (var f in Fields)
{
if (!string.IsNullOrWhiteSpace(f.Name) && !string.IsNullOrWhiteSpace(f.Value))
embed.AddField(efb => efb.WithName(f.Name).WithValue(f.Value).WithIsInline(f.Inline));
}
return embed;
}
public static bool TryParse(string input, out CREmbed embed)
{
embed = null;
if (string.IsNullOrWhiteSpace(input) || !input.Trim().StartsWith('{'))
return false;
try
{
var crembed = JsonConvert.DeserializeObject<CREmbed>(input);
if (crembed.Fields != null && crembed.Fields.Length > 0)
foreach (var f in crembed.Fields)
{
f.Name = f.Name.TrimTo(256);
f.Value = f.Value.TrimTo(1024);
}
if (!crembed.IsValid)
return false;
embed = crembed;
return true;
}
catch
{
return false;
}
}
}
public class CREmbedField
{
public string Name { get; set; }
public string Value { get; set; }
public bool Inline { get; set; }
}
public class CREmbedFooter
{
public string Text { get; set; }
public string IconUrl { get; set; }
[JsonProperty("icon_url")]
private string Icon_Url { set => IconUrl = value; }
}
public class CREmbedAuthor
{
public string Name { get; set; }
public string IconUrl { get; set; }
[JsonProperty("icon_url")]
private string Icon_Url { set => IconUrl = value; }
public string Url { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using Newtonsoft.Json;
namespace WizBot.Core.Common
{
public class CmdStrings
{
public string[] Usages { get; }
public string Description { get; }
[JsonConstructor]
public CmdStrings(
[JsonProperty("args")] string[] usages,
[JsonProperty("desc")] string description
)
{
Usages = usages;
Description = description;
}
}
}

View File

@ -0,0 +1,772 @@
// License MIT
// Source: https://github.com/i3arnon/ConcurrentHashSet
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace WizBot.Common.Collections
{
/// <summary>
/// Represents a thread-safe hash-based unique collection.
/// </summary>
/// <typeparam name="T">The type of the items in the collection.</typeparam>
/// <remarks>
/// All public members of <see cref="ConcurrentHashSet{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T>
{
private const int DefaultCapacity = 31;
private const int MaxLockNumber = 1024;
private readonly IEqualityComparer<T> _comparer;
private readonly bool _growLockArray;
private int _budget;
private volatile Tables _tables;
private static int DefaultConcurrencyLevel => PlatformHelper.ProcessorCount;
/// <summary>
/// Gets the number of items contained in the <see
/// cref="ConcurrentHashSet{T}"/>.
/// </summary>
/// <value>The number of items contained in the <see
/// cref="ConcurrentHashSet{T}"/>.</value>
/// <remarks>Count has snapshot semantics and represents the number of items in the <see
/// cref="ConcurrentHashSet{T}"/>
/// at the moment when Count was accessed.</remarks>
public int Count
{
get
{
var count = 0;
var acquiredLocks = 0;
try
{
AcquireAllLocks(ref acquiredLocks);
for (var i = 0; i < _tables.CountPerLock.Length; i++)
{
count += _tables.CountPerLock[i];
}
}
finally
{
ReleaseLocks(0, acquiredLocks);
}
return count;
}
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentHashSet{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentHashSet{T}"/> is empty; otherwise,
/// false.</value>
public bool IsEmpty
{
get
{
var acquiredLocks = 0;
try
{
AcquireAllLocks(ref acquiredLocks);
for (var i = 0; i < _tables.CountPerLock.Length; i++)
{
if (_tables.CountPerLock[i] != 0)
{
return false;
}
}
}
finally
{
ReleaseLocks(0, acquiredLocks);
}
return true;
}
}
/// <summary>
/// Initializes a new instance of the <see
/// cref="ConcurrentHashSet{T}"/>
/// class that is empty, has the default concurrency level, has the default initial capacity, and
/// uses the default comparer for the item type.
/// </summary>
public ConcurrentHashSet()
: this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer<T>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see
/// cref="ConcurrentHashSet{T}"/>
/// class that is empty, has the specified concurrency level and capacity, and uses the default
/// comparer for the item type.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentHashSet{T}"/> concurrently.</param>
/// <param name="capacity">The initial number of elements that the <see
/// cref="ConcurrentHashSet{T}"/>
/// can contain.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="concurrencyLevel"/> is
/// less than 1.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="capacity"/> is less than
/// 0.</exception>
public ConcurrentHashSet(int concurrencyLevel, int capacity)
: this(concurrencyLevel, capacity, false, EqualityComparer<T>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentHashSet{T}"/>
/// class that contains elements copied from the specified <see
/// cref="T:System.Collections.IEnumerable{T}"/>, has the default concurrency
/// level, has the default initial capacity, and uses the default comparer for the item type.
/// </summary>
/// <param name="collection">The <see
/// cref="T:System.Collections.IEnumerable{T}"/> whose elements are copied to
/// the new
/// <see cref="ConcurrentHashSet{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference.</exception>
public ConcurrentHashSet(IEnumerable<T> collection)
: this(collection, EqualityComparer<T>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentHashSet{T}"/>
/// class that is empty, has the specified concurrency level and capacity, and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>.
/// </summary>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>
/// implementation to use when comparing items.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
public ConcurrentHashSet(IEqualityComparer<T> comparer)
: this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentHashSet{T}"/>
/// class that contains elements copied from the specified <see
/// cref="T:System.Collections.IEnumerable"/>, has the default concurrency level, has the default
/// initial capacity, and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>.
/// </summary>
/// <param name="collection">The <see
/// cref="T:System.Collections.IEnumerable{T}"/> whose elements are copied to
/// the new
/// <see cref="ConcurrentHashSet{T}"/>.</param>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>
/// implementation to use when comparing items.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="collection"/> is a null reference
/// (Nothing in Visual Basic). -or-
/// <paramref name="comparer"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ConcurrentHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
: this(comparer)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentHashSet{T}"/>
/// class that contains elements copied from the specified <see cref="T:System.Collections.IEnumerable"/>,
/// has the specified concurrency level, has the specified initial capacity, and uses the specified
/// <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentHashSet{T}"/> concurrently.</param>
/// <param name="collection">The <see cref="T:System.Collections.IEnumerable{T}"/> whose elements are copied to the new
/// <see cref="ConcurrentHashSet{T}"/>.</param>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/> implementation to use
/// when comparing items.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="collection"/> is a null reference.
/// -or-
/// <paramref name="comparer"/> is a null reference.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="concurrencyLevel"/> is less than 1.
/// </exception>
public ConcurrentHashSet(int concurrencyLevel, IEnumerable<T> collection, IEqualityComparer<T> comparer)
: this(concurrencyLevel, DefaultCapacity, false, comparer)
{
if (collection == null) throw new ArgumentNullException(nameof(collection));
if (comparer == null) throw new ArgumentNullException(nameof(comparer));
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentHashSet{T}"/>
/// class that is empty, has the specified concurrency level, has the specified initial capacity, and
/// uses the specified <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>.
/// </summary>
/// <param name="concurrencyLevel">The estimated number of threads that will update the
/// <see cref="ConcurrentHashSet{T}"/> concurrently.</param>
/// <param name="capacity">The initial number of elements that the <see
/// cref="ConcurrentHashSet{T}"/>
/// can contain.</param>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer{T}"/>
/// implementation to use when comparing items.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="concurrencyLevel"/> is less than 1. -or-
/// <paramref name="capacity"/> is less than 0.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="comparer"/> is a null reference.</exception>
public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer<T> comparer)
: this(concurrencyLevel, capacity, false, comparer)
{
}
private ConcurrentHashSet(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<T> comparer)
{
if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException(nameof(concurrencyLevel));
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
// The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
// any buckets.
if (capacity < concurrencyLevel)
{
capacity = concurrencyLevel;
}
var locks = new object[concurrencyLevel];
for (var i = 0; i < locks.Length; i++)
{
locks[i] = new object();
}
var countPerLock = new int[locks.Length];
var buckets = new Node[capacity];
_tables = new Tables(buckets, locks, countPerLock);
_growLockArray = growLockArray;
_budget = buckets.Length / locks.Length;
_comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));
}
/// <summary>
/// Adds the specified item to the <see cref="ConcurrentHashSet{T}"/>.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>true if the items was added to the <see cref="ConcurrentHashSet{T}"/>
/// successfully; false if it already exists.</returns>
/// <exception cref="T:System.OverflowException">The <see cref="ConcurrentHashSet{T}"/>
/// contains too many items.</exception>
public bool Add(T item) =>
AddInternal(item, _comparer.GetHashCode(item), true);
/// <summary>
/// Removes all items from the <see cref="ConcurrentHashSet{T}"/>.
/// </summary>
public void Clear()
{
var locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
var newTables = new Tables(new Node[DefaultCapacity], _tables.Locks, new int[_tables.CountPerLock.Length]);
_tables = newTables;
_budget = Math.Max(1, newTables.Buckets.Length / newTables.Locks.Length);
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
/// <summary>
/// Determines whether the <see cref="ConcurrentHashSet{T}"/> contains the specified
/// item.
/// </summary>
/// <param name="item">The item to locate in the <see cref="ConcurrentHashSet{T}"/>.</param>
/// <returns>true if the <see cref="ConcurrentHashSet{T}"/> contains the item; otherwise, false.</returns>
public bool Contains(T item)
{
var hashcode = _comparer.GetHashCode(item);
// We must capture the _buckets field in a local variable. It is set to a new table on each table resize.
var tables = _tables;
var bucketNo = GetBucket(hashcode, tables.Buckets.Length);
// We can get away w/out a lock here.
// The Volatile.Read ensures that the load of the fields of 'n' doesn't move before the load from buckets[i].
var current = Volatile.Read(ref tables.Buckets[bucketNo]);
while (current != null)
{
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
return true;
}
current = current.Next;
}
return false;
}
/// <summary>
/// Attempts to remove the item from the <see cref="ConcurrentHashSet{T}"/>.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns>true if an item was removed successfully; otherwise, false.</returns>
public bool TryRemove(T item)
{
var hashcode = _comparer.GetHashCode(item);
while (true)
{
var tables = _tables;
GetBucketAndLockNo(hashcode, out var bucketNo, out var lockNo, tables.Buckets.Length, tables.Locks.Length);
lock (tables.Locks[lockNo])
{
// If the table just got resized, we may not be holding the right lock, and must retry.
// This should be a rare occurrence.
if (tables != _tables)
{
continue;
}
Node previous = null;
for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next)
{
Debug.Assert((previous == null && current == tables.Buckets[bucketNo]) || previous.Next == current);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
if (previous == null)
{
Volatile.Write(ref tables.Buckets[bucketNo], current.Next);
}
else
{
previous.Next = current.Next;
}
tables.CountPerLock[lockNo]--;
return true;
}
previous = current;
}
}
return false;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>Returns an enumerator that iterates through the <see
/// cref="ConcurrentHashSet{T}"/>.</summary>
/// <returns>An enumerator for the <see cref="ConcurrentHashSet{T}"/>.</returns>
/// <remarks>
/// The enumerator returned from the collection is safe to use concurrently with
/// reads and writes to the collection, however it does not represent a moment-in-time snapshot
/// of the collection. The contents exposed through the enumerator may contain modifications
/// made to the collection after <see cref="GetEnumerator"/> was called.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
var buckets = _tables.Buckets;
for (var i = 0; i < buckets.Length; i++)
{
// The Volatile.Read ensures that the load of the fields of 'current' doesn't move before the load from buckets[i].
var current = Volatile.Read(ref buckets[i]);
while (current != null)
{
yield return current.Item;
current = current.Next;
}
}
}
void ICollection<T>.Add(T item) => Add(item);
bool ICollection<T>.IsReadOnly => false;
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
var locksAcquired = 0;
try
{
AcquireAllLocks(ref locksAcquired);
var count = 0;
for (var i = 0; i < _tables.Locks.Length && count >= 0; i++)
{
count += _tables.CountPerLock[i];
}
if (array.Length - count < arrayIndex || count < 0) //"count" itself or "count + arrayIndex" can overflow
{
throw new ArgumentException("The index is equal to or greater than the length of the array, or the number of elements in the set is greater than the available space from index to the end of the destination array.");
}
CopyToItems(array, arrayIndex);
}
finally
{
ReleaseLocks(0, locksAcquired);
}
}
bool ICollection<T>.Remove(T item) => TryRemove(item);
private void InitializeFromCollection(IEnumerable<T> collection)
{
foreach (var item in collection)
{
AddInternal(item, _comparer.GetHashCode(item), false);
}
if (_budget == 0)
{
_budget = _tables.Buckets.Length / _tables.Locks.Length;
}
}
private bool AddInternal(T item, int hashcode, bool acquireLock)
{
while (true)
{
var tables = _tables;
GetBucketAndLockNo(hashcode, out var bucketNo, out var lockNo, tables.Buckets.Length, tables.Locks.Length);
var resizeDesired = false;
var lockTaken = false;
try
{
if (acquireLock)
Monitor.Enter(tables.Locks[lockNo], ref lockTaken);
// If the table just got resized, we may not be holding the right lock, and must retry.
// This should be a rare occurrence.
if (tables != _tables)
{
continue;
}
// Try to find this item in the bucket
Node previous = null;
for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next)
{
Debug.Assert((previous == null && current == tables.Buckets[bucketNo]) || previous.Next == current);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
return false;
}
previous = current;
}
// The item was not found in the bucket. Insert the new item.
Volatile.Write(ref tables.Buckets[bucketNo], new Node(item, hashcode, tables.Buckets[bucketNo]));
checked
{
tables.CountPerLock[lockNo]++;
}
//
// If the number of elements guarded by this lock has exceeded the budget, resize the bucket table.
// It is also possible that GrowTable will increase the budget but won't resize the bucket table.
// That happens if the bucket table is found to be poorly utilized due to a bad hash function.
//
if (tables.CountPerLock[lockNo] > _budget)
{
resizeDesired = true;
}
}
finally
{
if (lockTaken)
Monitor.Exit(tables.Locks[lockNo]);
}
//
// The fact that we got here means that we just performed an insertion. If necessary, we will grow the table.
//
// Concurrency notes:
// - Notice that we are not holding any locks at when calling GrowTable. This is necessary to prevent deadlocks.
// - As a result, it is possible that GrowTable will be called unnecessarily. But, GrowTable will obtain lock 0
// and then verify that the table we passed to it as the argument is still the current table.
//
if (resizeDesired)
{
GrowTable(tables);
}
return true;
}
}
private static int GetBucket(int hashcode, int bucketCount)
{
var bucketNo = (hashcode & 0x7fffffff) % bucketCount;
Debug.Assert(bucketNo >= 0 && bucketNo < bucketCount);
return bucketNo;
}
private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
{
bucketNo = (hashcode & 0x7fffffff) % bucketCount;
lockNo = bucketNo % lockCount;
Debug.Assert(bucketNo >= 0 && bucketNo < bucketCount);
Debug.Assert(lockNo >= 0 && lockNo < lockCount);
}
private void GrowTable(Tables tables)
{
const int maxArrayLength = 0X7FEFFFFF;
var locksAcquired = 0;
try
{
// The thread that first obtains _locks[0] will be the one doing the resize operation
AcquireLocks(0, 1, ref locksAcquired);
// Make sure nobody resized the table while we were waiting for lock 0:
if (tables != _tables)
{
// We assume that since the table reference is different, it was already resized (or the budget
// was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
// we will have to revisit this logic.
return;
}
// Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
long approxCount = 0;
for (var i = 0; i < tables.CountPerLock.Length; i++)
{
approxCount += tables.CountPerLock[i];
}
//
// If the bucket array is too empty, double the budget instead of resizing the table
//
if (approxCount < tables.Buckets.Length / 4)
{
_budget = 2 * _budget;
if (_budget < 0)
{
_budget = int.MaxValue;
}
return;
}
// Compute the new table size. We find the smallest integer larger than twice the previous table size, and not divisible by
// 2,3,5 or 7. We can consider a different table-sizing policy in the future.
var newLength = 0;
var maximizeTableSize = false;
try
{
checked
{
// Double the size of the buckets table and add one, so that we have an odd integer.
newLength = tables.Buckets.Length * 2 + 1;
// Now, we only need to check odd integers, and find the first that is not divisible
// by 3, 5 or 7.
while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
{
newLength += 2;
}
Debug.Assert(newLength % 2 != 0);
if (newLength > maxArrayLength)
{
maximizeTableSize = true;
}
}
}
catch (OverflowException)
{
maximizeTableSize = true;
}
if (maximizeTableSize)
{
newLength = maxArrayLength;
// We want to make sure that GrowTable will not be called again, since table is at the maximum size.
// To achieve that, we set the budget to int.MaxValue.
//
// (There is one special case that would allow GrowTable() to be called in the future:
// calling Clear() on the ConcurrentHashSet will shrink the table and lower the budget.)
_budget = int.MaxValue;
}
// Now acquire all other locks for the table
AcquireLocks(1, tables.Locks.Length, ref locksAcquired);
var newLocks = tables.Locks;
// Add more locks
if (_growLockArray && tables.Locks.Length < MaxLockNumber)
{
newLocks = new object[tables.Locks.Length * 2];
Array.Copy(tables.Locks, 0, newLocks, 0, tables.Locks.Length);
for (var i = tables.Locks.Length; i < newLocks.Length; i++)
{
newLocks[i] = new object();
}
}
var newBuckets = new Node[newLength];
var newCountPerLock = new int[newLocks.Length];
// Copy all data into a new table, creating new nodes for all elements
for (var i = 0; i < tables.Buckets.Length; i++)
{
var current = tables.Buckets[i];
while (current != null)
{
var next = current.Next;
GetBucketAndLockNo(current.Hashcode, out var newBucketNo, out var newLockNo, newBuckets.Length, newLocks.Length);
newBuckets[newBucketNo] = new Node(current.Item, current.Hashcode, newBuckets[newBucketNo]);
checked
{
newCountPerLock[newLockNo]++;
}
current = next;
}
}
// Adjust the budget
_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
// Replace tables with the new versions
_tables = new Tables(newBuckets, newLocks, newCountPerLock);
}
finally
{
// Release all locks that we took earlier
ReleaseLocks(0, locksAcquired);
}
}
public int RemoveWhere(Func<T, bool> predicate)
{
var elems = this.Where(predicate);
var removed = 0;
foreach (var elem in elems)
{
if (this.TryRemove(elem))
removed++;
}
return removed;
}
private void AcquireAllLocks(ref int locksAcquired)
{
// First, acquire lock 0
AcquireLocks(0, 1, ref locksAcquired);
// Now that we have lock 0, the _locks array will not change (i.e., grow),
// and so we can safely read _locks.Length.
AcquireLocks(1, _tables.Locks.Length, ref locksAcquired);
Debug.Assert(locksAcquired == _tables.Locks.Length);
}
private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
{
Debug.Assert(fromInclusive <= toExclusive);
var locks = _tables.Locks;
for (var i = fromInclusive; i < toExclusive; i++)
{
var lockTaken = false;
try
{
Monitor.Enter(locks[i], ref lockTaken);
}
finally
{
if (lockTaken)
{
locksAcquired++;
}
}
}
}
private void ReleaseLocks(int fromInclusive, int toExclusive)
{
Debug.Assert(fromInclusive <= toExclusive);
for (var i = fromInclusive; i < toExclusive; i++)
{
Monitor.Exit(_tables.Locks[i]);
}
}
private void CopyToItems(T[] array, int index)
{
var buckets = _tables.Buckets;
for (var i = 0; i < buckets.Length; i++)
{
for (var current = buckets[i]; current != null; current = current.Next)
{
array[index] = current.Item;
index++; //this should never flow, CopyToItems is only called when there's no overflow risk
}
}
}
private sealed class Tables
{
public readonly Node[] Buckets;
public readonly object[] Locks;
public volatile int[] CountPerLock;
public Tables(Node[] buckets, object[] locks, int[] countPerLock)
{
Buckets = buckets;
Locks = locks;
CountPerLock = countPerLock;
}
}
private sealed class Node
{
public readonly T Item;
public readonly int Hashcode;
public volatile Node Next;
public Node(T item, int hashcode, Node next)
{
Item = item;
Hashcode = hashcode;
Next = next;
}
}
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace WizBot.Common.Collections
{
public static class DisposableReadOnlyListExtensions
{
public static IDisposableReadOnlyList<T> AsDisposable<T>(this IReadOnlyList<T> arr) where T : IDisposable
=> new DisposableReadOnlyList<T>(arr);
public static IDisposableReadOnlyList<KeyValuePair<TKey, TValue>> AsDisposable<TKey, TValue>(this IReadOnlyList<KeyValuePair<TKey, TValue>> arr) where TValue : IDisposable
=> new DisposableReadOnlyList<TKey, TValue>(arr);
}
public interface IDisposableReadOnlyList<T> : IReadOnlyList<T>, IDisposable
{
}
public sealed class DisposableReadOnlyList<T> : IDisposableReadOnlyList<T>
where T : IDisposable
{
private readonly IReadOnlyList<T> _arr;
public int Count => _arr.Count;
public T this[int index] => _arr[index];
public DisposableReadOnlyList(IReadOnlyList<T> arr)
{
this._arr = arr;
}
public IEnumerator<T> GetEnumerator()
=> _arr.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> _arr.GetEnumerator();
public void Dispose()
{
foreach (var item in _arr)
{
item.Dispose();
}
}
}
public sealed class DisposableReadOnlyList<T, U> : IDisposableReadOnlyList<KeyValuePair<T, U>>
where U : IDisposable
{
private readonly IReadOnlyList<KeyValuePair<T, U>> _arr;
public int Count => _arr.Count;
KeyValuePair<T, U> IReadOnlyList<KeyValuePair<T, U>>.this[int index] => _arr[index];
public DisposableReadOnlyList(IReadOnlyList<KeyValuePair<T, U>> arr)
{
this._arr = arr;
}
public IEnumerator<KeyValuePair<T, U>> GetEnumerator() =>
_arr.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
_arr.GetEnumerator();
public void Dispose()
{
foreach (var item in _arr)
{
item.Value.Dispose();
}
}
}
}

View File

@ -0,0 +1,141 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using WizBot.Core.Services.Database.Models;
namespace WizBot.Common.Collections
{
public class IndexedCollection<T> : IList<T> where T : class, IIndexed
{
public List<T> Source { get; }
private readonly object _locker = new object();
public int Count => Source.Count;
public bool IsReadOnly => false;
public int IndexOf(T item) => item.Index;
public IndexedCollection()
{
Source = new List<T>();
}
public IndexedCollection(IEnumerable<T> source)
{
lock (_locker)
{
Source = source.OrderBy(x => x.Index).ToList();
UpdateIndexes();
}
}
public void UpdateIndexes()
{
lock (_locker)
{
for (var i = 0; i < Source.Count; i++)
{
if (Source[i].Index != i)
Source[i].Index = i;
}
}
}
public static implicit operator List<T>(IndexedCollection<T> x) =>
x.Source;
public List<T> ToList() => Source.ToList();
public IEnumerator<T> GetEnumerator() =>
Source.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
Source.GetEnumerator();
public void Add(T item)
{
lock (_locker)
{
item.Index = Source.Count;
Source.Add(item);
}
}
public virtual void Clear()
{
lock (_locker)
{
Source.Clear();
}
}
public bool Contains(T item)
{
lock (_locker)
{
return Source.Contains(item);
}
}
public void CopyTo(T[] array, int arrayIndex)
{
lock (_locker)
{
Source.CopyTo(array, arrayIndex);
}
}
public virtual bool Remove(T item)
{
bool removed;
lock (_locker)
{
if (removed = Source.Remove(item))
{
for (int i = 0; i < Source.Count; i++)
{
if (Source[i].Index != i)
Source[i].Index = i;
}
}
}
return removed;
}
public virtual void Insert(int index, T item)
{
lock (_locker)
{
Source.Insert(index, item);
for (int i = index; i < Source.Count; i++)
{
Source[i].Index = i;
}
}
}
public virtual void RemoveAt(int index)
{
lock (_locker)
{
Source.RemoveAt(index);
for (int i = index; i < Source.Count; i++)
{
Source[i].Index = i;
}
}
}
public virtual T this[int index]
{
get { return Source[index]; }
set
{
lock (_locker)
{
value.Index = index;
Source[index] = value;
}
}
}
}
}

View File

@ -0,0 +1,9 @@
namespace WizBot.Common
{
public class CommandData
{
public string Cmd { get; set; }
public string Desc { get; set; }
public string[] Usage { get; set; }
}
}

View File

@ -0,0 +1,166 @@
using System.Collections.Generic;
using System.Globalization;
using WizBot.Common.Yml;
using SixLabors.ImageSharp.PixelFormats;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
namespace WizBot.Core.Common.Configs
{
public sealed class BotConfig
{
[Comment(@"DO NOT CHANGE")]
public int Version { get; set; }
[Comment(@"Most commands, when executed, have a small colored line
next to the response. The color depends whether the command
is completed, errored or in progress (pending)
Color settings below are for the color of those lines.
To get color's hex, you can go here https://htmlcolorcodes.com/
and copy the hex code fo your selected color (marked as #)")]
public ColorConfig Color { get; set; }
[Comment("Default bot language. It has to be in the list of supported languages (.langli)")]
public CultureInfo DefaultLocale { get; set; }
[Comment(@"Style in which executed commands will show up in the console.
Allowed values: Simple, Normal, None")]
public ConsoleOutputType ConsoleOutputType { get; set; }
// [Comment(@"For what kind of updates will the bot check.
// Allowed values: Release, Commit, None")]
// public UpdateCheckType CheckForUpdates { get; set; }
// [Comment(@"How often will the bot check for updates, in hours")]
// public int CheckUpdateInterval { get; set; }
[Comment(@"Do you want any messages sent by users in Bot's DM to be forwarded to the owner(s)?")]
public bool ForwardMessages { get; set; }
[Comment(@"Do you want the message to be forwarded only to the first owner specified in the list of owners (in creds.yml),
or all owners? (this might cause the bot to lag if there's a lot of owners specified)")]
public bool ForwardToAllOwners { get; set; }
[Comment(@"When a user DMs the bot with a message which is not a command
they will receive this message. Leave empty for no response. The string which will be sent whenever someone DMs the bot.
Supports embeds. How it looks: https://puu.sh/B0BLV.png")]
[YamlMember(ScalarStyle = ScalarStyle.Literal)]
public string DmHelpText { get; set; }
[Comment(@"This is the response for the .h command")]
[YamlMember(ScalarStyle = ScalarStyle.Literal)]
public string HelpText { get; set; }
[Comment(@"List of modules and commands completely blocked on the bot")]
public BlockedConfig Blocked { get; set; }
[Comment(@"Which string will be used to recognize the commands")]
public string Prefix { get; set; }
[Comment(@"Toggles whether your bot will group greet/bye messages into a single message every 5 seconds.
1st user who joins will get greeted immediately
If more users join within the next 5 seconds, they will be greeted in groups of 5.
This will cause %user.mention% and other placeholders to be replaced with multiple users.
Keep in mind this might break some of your embeds - for example if you have %user.avatar% in the thumbnail,
it will become invalid, as it will resolve to a list of avatars of grouped users.
note: This setting is primarily used if you're afraid of raids, or you're running medium/large bots where some
servers might get hundreds of people join at once. This is used to prevent the bot from getting ratelimited,
and (slightly) reduce the greet spam in those servers.")]
public bool GroupGreets { get; set; }
[Comment(@"Whether the bot will rotate through all specified statuses.
This setting can be changed via .rots command.
See RotatingStatuses submodule in Administration.")]
public bool RotateStatuses { get; set; }
// [Comment(@"Whether the prefix will be a suffix, or prefix.
// For example, if your prefix is ! you will run a command called 'cash' by typing either
// '!cash @Someone' if your prefixIsSuffix: false or
// 'cash @Someone!' if your prefixIsSuffix: true")]
// public bool PrefixIsSuffix { get; set; }
// public string Prefixed(string text) => PrefixIsSuffix
// ? text + Prefix
// : Prefix + text;
public string Prefixed(string text)
=> Prefix + text;
public BotConfig()
{
Version = 1;
var color = new ColorConfig();
Color = color;
DefaultLocale = new CultureInfo("en-US");
ConsoleOutputType = ConsoleOutputType.Normal;
ForwardMessages = false;
ForwardToAllOwners = false;
DmHelpText = @"{""description"": ""Type `%prefix%h` for help.""}";
HelpText = @"{
""title"": ""To invite me to your server, use this link"",
""description"": ""https://discordapp.com/oauth2/authorize?client_id={0}&scope=bot&permissions=66186303"",
""color"": 53380,
""thumbnail"": ""https://i.imgur.com/Q9PEzXv.png"",
""fields"": [
{
""name"": ""Useful help commands"",
""value"": ""`%bot.prefix%modules` Lists all bot modules.
`%prefix%h CommandName` Shows some help about a specific command.
`%prefix%commands ModuleName` Lists all commands in a module."",
""inline"": false
},
{
""name"": ""List of all Commands"",
""value"": ""https://commands.wizbot.cc/"",
""inline"": false
},
{
""name"": ""WizBot Support Server"",
""value"": ""https://wizbot.cc/discord "",
""inline"": true
}
]
}";
var blocked = new BlockedConfig();
Blocked = blocked;
Prefix = ".";
RotateStatuses = false;
GroupGreets = false;
}
}
public class BlockedConfig
{
public HashSet<string> Commands { get; set; }
public HashSet<string> Modules { get; set; }
public BlockedConfig()
{
Modules = new HashSet<string>();
Commands = new HashSet<string>();
}
}
public class ColorConfig
{
[Comment(@"Color used for embed responses when command successfully executes")]
public Rgba32 Ok { get; set; }
[Comment(@"Color used for embed responses when command has an error")]
public Rgba32 Error { get; set; }
[Comment(@"Color used for embed responses while command is doing work or is in progress")]
public Rgba32 Pending { get; set; }
public ColorConfig()
{
Ok = Rgba32.ParseHex("ab40cd");
Error = Rgba32.ParseHex("ee281f");
Pending = Rgba32.ParseHex("faa61a");
}
}
public enum ConsoleOutputType
{
Normal = 0,
Simple = 1,
None = 2,
}
}

View File

@ -0,0 +1,18 @@
namespace WizBot.Core.Common.Configs
{
/// <summary>
/// Base interface for available config serializers
/// </summary>
public interface IConfigSeria
{
/// <summary>
/// Serialize the object to string
/// </summary>
public string Serialize<T>(T obj);
/// <summary>
/// Deserialize string data into an object of the specified type
/// </summary>
public T Deserialize<T>(string data);
}
}

View File

@ -0,0 +1,43 @@
using WizBot.Core.Services;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Discord;
namespace WizBot.Core.Common
{
public class DownloadTracker : INService
{
private ConcurrentDictionary<ulong, DateTime> LastDownloads { get; } = new ConcurrentDictionary<ulong, DateTime>();
private SemaphoreSlim downloadUsersSemaphore = new SemaphoreSlim(1, 1);
/// <summary>
/// Ensures all users on the specified guild were downloaded within the last hour.
/// </summary>
/// <param name="guild">Guild to check and potentially download users from</param>
/// <returns>Task representing download state</returns>
public async Task EnsureUsersDownloadedAsync(IGuild guild)
{
await downloadUsersSemaphore.WaitAsync();
try
{
var now = DateTime.UtcNow;
// download once per hour at most
var added = LastDownloads.AddOrUpdate(
guild.Id,
now,
(key, old) => (now - old) > TimeSpan.FromHours(1) ? now : old);
// means that this entry was just added - download the users
if (added == now)
await guild.DownloadUsersAsync();
}
finally
{
downloadUsersSemaphore.Release();
}
}
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using WizBot.Core.Modules.Music;
using WizBot.Core.Services;
using WizBot.Modules.Administration.Services;
using WizBot.Modules.Music.Resolvers;
using WizBot.Modules.Music.Services;
namespace WizBot.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddBotStringsServices(this IServiceCollection services)
=> services
.AddSingleton<IStringsSource, LocalFileStringsSource>()
.AddSingleton<IBotStringsProvider, LocalBotStringsProvider>()
.AddSingleton<IBotStrings, BotStrings>();
public static IServiceCollection AddConfigServices(this IServiceCollection services)
{
var baseType = typeof(ConfigServiceBase<>);
foreach (var type in Assembly.GetCallingAssembly().ExportedTypes.Where(x => x.IsSealed))
{
if (type.BaseType?.IsGenericType == true && type.BaseType.GetGenericTypeDefinition() == baseType)
{
services.AddSingleton(type);
services.AddSingleton(x => (IConfigService)x.GetRequiredService(type));
}
}
return services;
}
public static IServiceCollection AddConfigMigrators(this IServiceCollection services)
=> services.AddSealedSubclassesOf(typeof(IConfigMigrator));
public static IServiceCollection AddMusic(this IServiceCollection services)
=> services
.AddSingleton<IMusicService, MusicService>()
.AddSingleton<ITrackResolveProvider, TrackResolveProvider>()
.AddSingleton<IYoutubeResolver, YtdlYoutubeResolver>()
.AddSingleton<ISoundcloudResolver, SoundcloudResolver>()
.AddSingleton<ILocalTrackResolver, LocalTrackResolver>()
.AddSingleton<IRadioResolver, RadioResolver>()
.AddSingleton<ITrackCacher, RedisTrackCacher>()
.AddSingleton<YtLoader>();
// consider using scrutor, because slightly different versions
// of this might be needed in several different places
public static IServiceCollection AddSealedSubclassesOf(this IServiceCollection services, Type baseType)
{
var subTypes = Assembly.GetCallingAssembly()
.ExportedTypes
.Where(type => type.IsSealed && baseType.IsAssignableFrom(type));
foreach (var subType in subTypes)
{
services.AddSingleton(baseType, subType);
}
return services;
}
}
}

View File

@ -0,0 +1,255 @@
using System;
namespace Discord
{
// just a copy paste from discord.net in order to rename it, for compatibility iwth v3 which is gonna use custom lib
// Summary:
// Defines the available permissions for a channel.
[Flags]
public enum GuildPerm : ulong
{
//
// Summary:
// Allows creation of instant invites.
CreateInstantInvite = 1,
//
// Summary:
// Allows kicking members.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
KickMembers = 2,
//
// Summary:
// Allows banning members.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
BanMembers = 4,
//
// Summary:
// Allows all permissions and bypasses channel permission overwrites.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
Administrator = 8,
//
// Summary:
// Allows management and editing of channels.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageChannels = 16,
//
// Summary:
// Allows management and editing of the guild.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageGuild = 32,
//
// Summary:
// Allows for the addition of reactions to messages.
AddReactions = 64,
//
// Summary:
// Allows for viewing of audit logs.
ViewAuditLog = 128,
PrioritySpeaker = 256,
ReadMessages = 1024,
ViewChannel = 1024,
SendMessages = 2048,
//
// Summary:
// Allows for sending of text-to-speech messages.
SendTTSMessages = 4096,
//
// Summary:
// Allows for deletion of other users messages.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageMessages = 8192,
//
// Summary:
// Allows links sent by users with this permission will be auto-embedded.
EmbedLinks = 16384,
//
// Summary:
// Allows for uploading images and files.
AttachFiles = 32768,
//
// Summary:
// Allows for reading of message history.
ReadMessageHistory = 65536,
//
// Summary:
// Allows for using the @everyone tag to notify all users in a channel, and the
// @here tag to notify all online users in a channel.
MentionEveryone = 131072,
//
// Summary:
// Allows the usage of custom emojis from other servers.
UseExternalEmojis = 262144,
//
// Summary:
// Allows for joining of a voice channel.
Connect = 1048576,
//
// Summary:
// Allows for speaking in a voice channel.
Speak = 2097152,
//
// Summary:
// Allows for muting members in a voice channel.
MuteMembers = 4194304,
//
// Summary:
// Allows for deafening of members in a voice channel.
DeafenMembers = 8388608,
//
// Summary:
// Allows for moving of members between voice channels.
MoveMembers = 16777216,
//
// Summary:
// Allows for using voice-activity-detection in a voice channel.
UseVAD = 33554432,
//
// Summary:
// Allows for modification of own nickname.
ChangeNickname = 67108864,
//
// Summary:
// Allows for modification of other users nicknames.
ManageNicknames = 134217728,
//
// Summary:
// Allows management and editing of roles.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageRoles = 268435456,
//
// Summary:
// Allows management and editing of webhooks.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageWebhooks = 536870912,
//
// Summary:
// Allows management and editing of emojis.
//
// Remarks:
// This permission requires the owner account to use two-factor authentication when
// used on a guild that has server-wide 2FA enabled.
ManageEmojis = 1073741824
}
//
// Summary:
// Defines the available permissions for a channel.
[Flags]
public enum ChannelPerm : ulong
{
//
// Summary:
// Allows creation of instant invites.
CreateInstantInvite = 1,
//
// Summary:
// Allows management and editing of channels.
ManageChannel = 16,
//
// Summary:
// Allows for the addition of reactions to messages.
AddReactions = 64,
PrioritySpeaker = 256,
//
// Summary:
// Allows for reading of messages. This flag is obsolete, use Discord.ChannelPermission.ViewChannel
// instead.
ReadMessages = 1024,
//
// Summary:
// Allows guild members to view a channel, which includes reading messages in text
// channels.
ViewChannel = 1024,
//
// Summary:
// Allows for sending messages in a channel.
SendMessages = 2048,
//
// Summary:
// Allows for sending of text-to-speech messages.
SendTTSMessages = 4096,
//
// Summary:
// Allows for deletion of other users messages.
ManageMessages = 8192,
//
// Summary:
// Allows links sent by users with this permission will be auto-embedded.
EmbedLinks = 16384,
//
// Summary:
// Allows for uploading images and files.
AttachFiles = 32768,
//
// Summary:
// Allows for reading of message history.
ReadMessageHistory = 65536,
//
// Summary:
// Allows for using the @everyone tag to notify all users in a channel, and the
// @here tag to notify all online users in a channel.
MentionEveryone = 131072,
//
// Summary:
// Allows the usage of custom emojis from other servers.
UseExternalEmojis = 262144,
//
// Summary:
// Allows for joining of a voice channel.
Connect = 1048576,
//
// Summary:
// Allows for speaking in a voice channel.
Speak = 2097152,
//
// Summary:
// Allows for muting members in a voice channel.
MuteMembers = 4194304,
//
// Summary:
// Allows for deafening of members in a voice channel.
DeafenMembers = 8388608,
//
// Summary:
// Allows for moving of members between voice channels.
MoveMembers = 16777216,
//
// Summary:
// Allows for using voice-activity-detection in a voice channel.
UseVAD = 33554432,
//
// Summary:
// Allows management and editing of roles.
ManageRoles = 268435456,
//
// Summary:
// Allows management and editing of webhooks.
ManageWebhooks = 536870912
}
}

View File

@ -0,0 +1,15 @@
using System;
namespace WizBot.Core.Common
{
public static class Helpers
{
public static void ReadErrorAndExit(int exitCode)
{
if (!Console.IsInputRedirected)
Console.ReadKey();
Environment.Exit(exitCode);
}
}
}

View File

@ -0,0 +1,7 @@
namespace WizBot.Core.Common
{
public interface IWizBotCommandOptions
{
void NormalizeOptions();
}
}

View File

@ -0,0 +1,49 @@
using System;
namespace WizBot.Core.Common
{
public class ImageUrls
{
public int Version { get; set; } = 2;
public CoinData Coins { get; set; }
public Uri[] Currency { get; set; }
public Uri[] Dice { get; set; }
public RategirlData Rategirl { get; set; }
public XpData Xp { get; set; }
//new
public RipData Rip { get; set; }
public SlotData Slots { get; set; }
public class RipData
{
public Uri Bg { get; set; }
public Uri Overlay { get; set; }
}
public class SlotData
{
public Uri[] Emojis { get; set; }
public Uri[] Numbers { get; set; }
public Uri Bg { get; set; }
}
public class CoinData
{
public Uri[] Heads { get; set; }
public Uri[] Tails { get; set; }
}
public class RategirlData
{
public Uri Matrix { get; set; }
public Uri Dot { get; set; }
}
public class XpData
{
public Uri Bg { get; set; }
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using SixLabors.ImageSharp.PixelFormats;
namespace WizBot.Core.Common.JsonConverters
{
public class Rgba32Converter : JsonConverter<Rgba32>
{
public override Rgba32 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return Rgba32.ParseHex(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, Rgba32 value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToHex());
}
}
public class CultureInfoConverter : JsonConverter<CultureInfo>
{
public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return new CultureInfo(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.Name);
}
}
}

View File

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace WizBot.Core.Common
{
public readonly struct kwum
{
private readonly char[] _data;
private const string ValidCharacters = "23456789abcdefghijkmnpqrstuvwxyz";
private static readonly HashSet<char> validCharacterSet = ValidCharacters.ToHashSet();
public kwum(in char c)
{
if (!IsValidChar(c))
throw new ArgumentException("Character needs to be a valid kwum character.", nameof(c));
_data = new[] { c };
}
public kwum(in ReadOnlySpan<char> input)
{
foreach (var c in input)
if (!IsValidChar(c))
throw new ArgumentException("All characters need to be a valid kwum characters.", nameof(c));
_data = input.ToArray();
}
/// <summary>
/// Unsafe, used only internally
/// </summary>
/// <param name="data">Array of characters</param>
private kwum(char[] data)
=> _data = data;
public static bool TryParse(in ReadOnlySpan<char> input, out kwum value)
{
value = default;
foreach (var c in input)
if (!IsValidChar(c))
return false;
value = new kwum(input.ToArray());
return true;
}
public static kwum operator +(kwum left, kwum right)
{
throw new NotImplementedException();
}
public static bool operator ==(kwum left, kwum right)
{
if (left._data is null)
return right._data is null;
if (right._data is null)
return false;
if (left._data.Length != right._data.Length)
return false;
for (var i = 0; i < left._data.Length; i++)
{
if (left._data[i] != right._data[i])
return false;
}
return true;
}
public static bool operator !=(kwum left, kwum right)
=> !(left == right);
public static bool IsValidChar(char c)
=> validCharacterSet.Contains(c);
public override string ToString()
=> new string(_data);
public override bool Equals(object obj)
=> obj is kwum kw && kw == this;
public override int GetHashCode()
{
HashCode hashCode = default;
if (_data is null)
return 0;
for (var i = _data.Length >= 8 ? _data.Length - 8 : 0; i < _data.Length; i++)
{
hashCode.Add(_data[i].GetHashCode());
}
return hashCode.ToHashCode();
}
}
}

View File

@ -0,0 +1,14 @@
using CommandLine;
namespace WizBot.Core.Common
{
public class LbOpts : IWizBotCommandOptions
{
[Option('c', "clean", Default = false, HelpText = "Only show users who are on the server.")]
public bool Clean { get; set; }
public void NormalizeOptions()
{
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Net;
using System.Runtime.CompilerServices;
using Discord.Net;
using Serilog;
namespace WizBot.Core.Common
{
public class LoginErrorHandler
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Handle(Exception ex)
{
Log.Fatal(ex, "A fatal error has occurred while attempting to connect to Discord");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Handle(HttpException ex)
{
switch (ex.HttpCode)
{
case HttpStatusCode.Unauthorized:
Log.Error("Your bot token is wrong.\n" +
"You can find the bot token under the Bot tab in the developer page.\n" +
"Fix your token in the credentials file and restart the bot");
break;
case HttpStatusCode.BadRequest:
Log.Error("Something has been incorrectly formatted in your credentials file.\n" +
"Use the JSON Guide as reference to fix it and restart the bot.");
Log.Error("If you are on Linux, make sure Redis is installed and running");
break;
case HttpStatusCode.RequestTimeout:
Log.Error("The request timed out. Make sure you have no external program blocking the bot " +
"from connecting to the internet");
break;
case HttpStatusCode.ServiceUnavailable:
case HttpStatusCode.InternalServerError:
Log.Error("Discord is having internal issues. Please, try again later");
break;
case HttpStatusCode.TooManyRequests:
Log.Error("Your bot has been ratelimited by Discord. Please, try again later.\n" +
"Global ratelimits usually last for an hour");
break;
default:
Log.Warning("An error occurred while attempting to connect to Discord");
break;
}
Log.Fatal(ex.ToString());
}
}
}

View File

@ -0,0 +1,23 @@
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace WizBot.Common.ModuleBehaviors
{
/// <summary>
/// Implemented by modules which block execution before anything is executed
/// </summary>
public interface IEarlyBehavior
{
int Priority { get; }
ModuleBehaviorType BehaviorType { get; }
Task<bool> RunBehavior(DiscordSocketClient client, IGuild guild, IUserMessage msg);
}
public enum ModuleBehaviorType
{
Blocker,
Executor,
}
}

View File

@ -0,0 +1,10 @@
using System.Threading.Tasks;
using Discord;
namespace WizBot.Common.ModuleBehaviors
{
public interface IInputTransformer
{
Task<string> TransformInput(IGuild guild, IMessageChannel channel, IUser user, string input);
}
}

View File

@ -0,0 +1,14 @@
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
namespace WizBot.Common.ModuleBehaviors
{
public interface ILateBlocker
{
public int Priority { get; }
Task<bool> TryBlockLate(DiscordSocketClient client, ICommandContext context,
string moduleName, CommandInfo command);
}
}

View File

@ -0,0 +1,14 @@
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace WizBot.Common.ModuleBehaviors
{
/// <summary>
/// Last thing to be executed, won't stop further executions
/// </summary>
public interface ILateExecutor
{
Task LateExecute(DiscordSocketClient client, IGuild guild, IUserMessage msg);
}
}

View File

@ -0,0 +1,34 @@
using Discord;
using Discord.WebSocket;
using System.Threading.Tasks;
namespace WizBot.Common.ModuleBehaviors
{
public struct ModuleBehaviorResult
{
public bool Blocked { get; set; }
public string NewInput { get; set; }
public static ModuleBehaviorResult None() => new ModuleBehaviorResult
{
Blocked = false,
NewInput = null,
};
public static ModuleBehaviorResult FromBlocked(bool blocked) => new ModuleBehaviorResult
{
Blocked = blocked,
NewInput = null,
};
}
public interface IModuleBehavior
{
/// <summary>
/// Negative priority means it will try to apply as early as possible
/// Positive priority menas it will try to apply as late as possible
/// </summary>
int Priority { get; }
Task<ModuleBehaviorResult> ApplyBehavior(DiscordSocketClient client, IGuild guild, IUserMessage msg);
}
}

View File

@ -0,0 +1,16 @@
using System.Threading.Tasks;
namespace WizBot.Common.ModuleBehaviors
{
/// <summary>
/// All services which need to execute something after
/// the bot is ready should implement this interface
/// </summary>
public interface IReadyExecutor
{
/// <summary>
/// Executed when bot is ready
/// </summary>
public Task OnReadyAsync();
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
namespace WizBot.Common
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class NoPublicBotAttribute : PreconditionAttribute
{
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
#if GLOBAL_WIZBOT
return Task.FromResult(PreconditionResult.FromError("Not available on the public bot"));
#else
return Task.FromResult(PreconditionResult.FromSuccess());
#endif
}
}
}

View File

@ -0,0 +1,24 @@
using CommandLine;
namespace WizBot.Core.Common
{
public static class OptionsParser
{
public static T ParseFrom<T>(string[] args) where T : IWizBotCommandOptions, new()
=> ParseFrom(new T(), args).Item1;
public static (T, bool) ParseFrom<T>(T options, string[] args) where T : IWizBotCommandOptions
{
using (var p = new Parser(x =>
{
x.HelpWriter = null;
}))
{
var res = p.ParseArguments<T>(args);
options = res.MapResult(x => x, x => options);
options.NormalizeOptions();
return (options, res.Tag == ParserResultType.Parsed);
}
}
}
}

View File

@ -0,0 +1,9 @@
namespace WizBot.Core.Common
{
public class OsuMapData
{
public string Title { get; set; }
public string Artist { get; set; }
public string Version { get; set; }
}
}

View File

@ -0,0 +1,41 @@
using Newtonsoft.Json;
namespace WizBot.Core.Common
{
public class OsuUserBests
{
[JsonProperty("beatmap_id")] public string BeatmapId { get; set; }
[JsonProperty("score_id")] public string ScoreId { get; set; }
[JsonProperty("score")] public string Score { get; set; }
[JsonProperty("maxcombo")] public string Maxcombo { get; set; }
[JsonProperty("count50")] public double Count50 { get; set; }
[JsonProperty("count100")] public double Count100 { get; set; }
[JsonProperty("count300")] public double Count300 { get; set; }
[JsonProperty("countmiss")] public int Countmiss { get; set; }
[JsonProperty("countkatu")] public double Countkatu { get; set; }
[JsonProperty("countgeki")] public double Countgeki { get; set; }
[JsonProperty("perfect")] public string Perfect { get; set; }
[JsonProperty("enabled_mods")] public int EnabledMods { get; set; }
[JsonProperty("user_id")] public string UserId { get; set; }
[JsonProperty("date")] public string Date { get; set; }
[JsonProperty("rank")] public string Rank { get; set; }
[JsonProperty("pp")] public double Pp { get; set; }
[JsonProperty("replay_available")] public string ReplayAvailable { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using System;
namespace WizBot.Common
{
public static class PlatformHelper
{
private const int ProcessorCountRefreshIntervalMs = 30000;
private static volatile int _processorCount;
private static volatile int _lastProcessorCountRefreshTicks;
public static int ProcessorCount {
get {
var now = Environment.TickCount;
if (_processorCount == 0 || (now - _lastProcessorCountRefreshTicks) >= ProcessorCountRefreshIntervalMs)
{
_processorCount = Environment.ProcessorCount;
_lastProcessorCountRefreshTicks = now;
}
return _processorCount;
}
}
}
}

View File

@ -0,0 +1,8 @@
namespace WizBot.Core.Common.Pokemon
{
public class PokemonNameId
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,40 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace WizBot.Core.Common.Pokemon
{
public class SearchPokemon
{
public class GenderRatioClass
{
public float M { get; set; }
public float F { get; set; }
}
public class BaseStatsClass
{
public int HP { get; set; }
public int ATK { get; set; }
public int DEF { get; set; }
public int SPA { get; set; }
public int SPD { get; set; }
public int SPE { get; set; }
public override string ToString() => $@"💚**HP:** {HP,-4} ⚔**ATK:** {ATK,-4} 🛡**DEF:** {DEF,-4}
**SPA:** {SPA,-4} 🎇**SPD:** {SPD,-4} 💨**SPE:** {SPE,-4}";
}
[JsonProperty("num")]
public int Id { get; set; }
public string Species { get; set; }
public string[] Types { get; set; }
public GenderRatioClass GenderRatio { get; set; }
public BaseStatsClass BaseStats { get; set; }
public Dictionary<string, string> Abilities { get; set; }
public float HeightM { get; set; }
public float WeightKg { get; set; }
public string Color { get; set; }
public string[] Evos { get; set; }
public string[] EggGroups { get; set; }
}
}

View File

@ -0,0 +1,10 @@
namespace WizBot.Core.Common.Pokemon
{
public class SearchPokemonAbility
{
public string Desc { get; set; }
public string ShortDesc { get; set; }
public string Name { get; set; }
public float Rating { get; set; }
}
}

View File

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WizBot.Core.Common
{
public class EventPubSub : IPubSub
{
private readonly Dictionary<string, Dictionary<Delegate, List<Func<object, ValueTask>>>> _actions
= new Dictionary<string, Dictionary<Delegate, List<Func<object, ValueTask>>>>();
private readonly object locker = new object();
public Task Sub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action)
{
Func<object, ValueTask> localAction = obj => action((TData) obj);
lock(locker)
{
Dictionary<Delegate, List<Func<object, ValueTask>>> keyActions;
if (!_actions.TryGetValue(key.Key, out keyActions))
{
keyActions = new Dictionary<Delegate, List<Func<object, ValueTask>>>();
_actions[key.Key] = keyActions;
}
List<Func<object, ValueTask>> sameActions;
if (!keyActions.TryGetValue(action, out sameActions))
{
sameActions = new List<Func<object, ValueTask>>();
keyActions[action] = sameActions;
}
sameActions.Add(localAction);
return Task.CompletedTask;
}
}
public Task Pub<TData>(in TypedKey<TData> key, TData data)
{
lock (locker)
{
if(_actions.TryGetValue(key.Key, out var actions))
{
// if this class ever gets used, this needs to be properly implemented
// 1. ignore all valuetasks which are completed
// 2. return task.whenall all other tasks
return Task.WhenAll(actions
.SelectMany(kvp => kvp.Value)
.Select(action => action(data).AsTask()));
}
return Task.CompletedTask;
}
}
public Task Unsub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action)
{
lock (locker)
{
// get subscriptions for this action
if (_actions.TryGetValue(key.Key, out var actions))
{
var hashCode = action.GetHashCode();
// get subscriptions which have the same action hash code
// note: having this as a list allows for multiple subscriptions of
// the same insance's/static method
if (actions.TryGetValue(action, out var sameActions))
{
// remove last subscription
sameActions.RemoveAt(sameActions.Count - 1);
// if the last subscription was the only subscription
// we can safely remove this action's dictionary entry
if (sameActions.Count == 0)
{
actions.Remove(action);
// if our dictionary has no more elements after
// removing the entry
// it's safe to remove it from the key's subscriptions
if (actions.Count == 0)
{
_actions.Remove(key.Key);
}
}
}
}
return Task.CompletedTask;
}
}
}
}

View File

@ -0,0 +1,11 @@
using System;
using System.Threading.Tasks;
namespace WizBot.Core.Common
{
public interface IPubSub
{
public Task Pub<TData>(in TypedKey<TData> key, TData data);
public Task Sub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action);
}
}

View File

@ -0,0 +1,8 @@
namespace WizBot.Core.Common
{
public interface ISeria
{
byte[] Serialize<T>(T data);
T Deserialize<T>(byte[] data);
}
}

View File

@ -0,0 +1,28 @@
using System.Text.Json;
using WizBot.Core.Common.JsonConverters;
namespace WizBot.Core.Common
{
public class JsonSeria : ISeria
{
private JsonSerializerOptions serializerOptions = new JsonSerializerOptions()
{
Converters =
{
new Rgba32Converter(),
new CultureInfoConverter(),
}
};
public byte[] Serialize<T>(T data)
=> JsonSerializer.SerializeToUtf8Bytes(data, serializerOptions);
public T Deserialize<T>(byte[] data)
{
if (data is null)
return default;
return JsonSerializer.Deserialize<T>(data, serializerOptions);
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Threading.Tasks;
using WizBot.Core.Services;
using WizBot.Extensions;
using Serilog;
using StackExchange.Redis;
namespace WizBot.Core.Common
{
public sealed class RedisPubSub : IPubSub
{
private readonly ConnectionMultiplexer _multi;
private readonly ISeria _serializer;
private readonly IBotCredentials _creds;
public RedisPubSub(ConnectionMultiplexer multi, ISeria serializer, IBotCredentials creds)
{
_multi = multi;
_serializer = serializer;
_creds = creds;
}
public Task Pub<TData>(in TypedKey<TData> key, TData data)
{
var serialized = _serializer.Serialize(data);
return _multi.GetSubscriber().PublishAsync($"{_creds.RedisKey()}:{key.Key}", serialized, CommandFlags.FireAndForget);
}
public Task Sub<TData>(in TypedKey<TData> key, Func<TData, ValueTask> action)
{
var eventName = key.Key;
return _multi.GetSubscriber().SubscribeAsync($"{_creds.RedisKey()}:{eventName}", async (ch, data) =>
{
try
{
var dataObj = _serializer.Deserialize<TData>(data);
await action(dataObj);
}
catch (Exception ex)
{
Log.Error($"Error handling the event {eventName}: {ex.Message}");
}
});
}
}
}

View File

@ -0,0 +1,29 @@
namespace WizBot.Core.Common
{
public readonly struct TypedKey<TData>
{
public readonly string Key;
public TypedKey(in string key)
{
Key = key;
}
public static implicit operator TypedKey<TData>(in string input)
=> new TypedKey<TData>(input);
public static implicit operator string(in TypedKey<TData> input)
=> input.Key;
public static bool operator ==(in TypedKey<TData> left, in TypedKey<TData> right)
=> left.Key == right.Key;
public static bool operator !=(in TypedKey<TData> left, in TypedKey<TData> right)
=> !(left == right);
public override bool Equals(object obj)
=> obj is TypedKey<TData> o && o == this;
public override int GetHashCode() => Key?.GetHashCode() ?? 0;
public override string ToString() => Key;
}
}

View File

@ -0,0 +1,38 @@
using System.Text.RegularExpressions;
using WizBot.Common.Yml;
using WizBot.Core.Common.Configs;
using YamlDotNet.Serialization;
namespace WizBot.Core.Common
{
public class YamlSeria : IConfigSeria
{
private readonly ISerializer _serializer;
private readonly IDeserializer _deserializer;
private static readonly Regex CodePointRegex
= new Regex(@"(\\U(?<code>[a-zA-Z0-9]{8})|\\u(?<code>[a-zA-Z0-9]{4})|\\x(?<code>[a-zA-Z0-9]{2}))",
RegexOptions.Compiled);
public YamlSeria()
{
_serializer = Yaml.Serializer;
_deserializer = Yaml.Deserializer;
}
public string Serialize<T>(T obj)
{
var escapedOutput = _serializer.Serialize(obj);
var output = CodePointRegex.Replace(escapedOutput, me =>
{
var str = me.Groups["code"].Value;
var newString = YamlHelper.UnescapeUnicodeCodePoint(str);
return newString;
});
return output;
}
public T Deserialize<T>(string data)
=> _deserializer.Deserialize<T>(data);
}
}

View File

@ -0,0 +1,255 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Extensions;
using WizBot.Modules.Administration.Services;
using WizBot.Modules.Music.Services;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace WizBot.Common.Replacements
{
public class ReplacementBuilder
{
private static readonly Regex rngRegex = new Regex("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%", RegexOptions.Compiled);
private ConcurrentDictionary<string, Func<string>> _reps = new ConcurrentDictionary<string, Func<string>>();
private ConcurrentDictionary<Regex, Func<Match, string>> _regex = new ConcurrentDictionary<Regex, Func<Match, string>>();
public ReplacementBuilder()
{
WithRngRegex();
}
public ReplacementBuilder WithDefault(IUser usr, IMessageChannel ch, SocketGuild g, DiscordSocketClient client)
{
return this.WithUser(usr)
.WithChannel(ch)
.WithServer(client, g)
.WithClient(client);
}
public ReplacementBuilder WithDefault(ICommandContext ctx) =>
WithDefault(ctx.User, ctx.Channel, ctx.Guild as SocketGuild, (DiscordSocketClient)ctx.Client);
public ReplacementBuilder WithMention(DiscordSocketClient client)
{
/*OBSOLETE*/
_reps.TryAdd("%mention%", () => $"<@{client.CurrentUser.Id}>");
/*NEW*/
_reps.TryAdd("%bot.mention%", () => client.CurrentUser.Mention);
return this;
}
public ReplacementBuilder WithClient(DiscordSocketClient client)
{
WithMention(client);
/*OBSOLETE*/
_reps.TryAdd("%shardid%", () => client.ShardId.ToString());
_reps.TryAdd("%time%", () => DateTime.Now.ToString("HH:mm " + TimeZoneInfo.Local.StandardName.GetInitials()));
/*NEW*/
_reps.TryAdd("%bot.status%", () => client.Status.ToString());
_reps.TryAdd("%bot.latency%", () => client.Latency.ToString());
_reps.TryAdd("%bot.name%", () => client.CurrentUser.Username);
_reps.TryAdd("%bot.fullname%", () => client.CurrentUser.ToString());
_reps.TryAdd("%bot.time%", () => DateTime.Now.ToString("HH:mm " + TimeZoneInfo.Local.StandardName.GetInitials()));
_reps.TryAdd("%bot.discrim%", () => client.CurrentUser.Discriminator);
_reps.TryAdd("%bot.id%", () => client.CurrentUser.Id.ToString());
_reps.TryAdd("%bot.avatar%", () => client.CurrentUser.RealAvatarUrl()?.ToString());
WithStats(client);
return this;
}
public ReplacementBuilder WithServer(DiscordSocketClient client, SocketGuild g)
{
/*OBSOLETE*/
_reps.TryAdd("%sid%", () => g == null ? "DM" : g.Id.ToString());
_reps.TryAdd("%server%", () => g == null ? "DM" : g.Name);
_reps.TryAdd("%members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server_time%", () =>
{
TimeZoneInfo to = TimeZoneInfo.Local;
if (g != null)
{
if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz))
to = tz.GetTimeZoneOrDefault(g.Id) ?? TimeZoneInfo.Local;
}
return TimeZoneInfo.ConvertTime(DateTime.UtcNow,
TimeZoneInfo.Utc,
to).ToString("HH:mm ") + to.StandardName.GetInitials();
});
/*NEW*/
_reps.TryAdd("%server.id%", () => g == null ? "DM" : g.Id.ToString());
_reps.TryAdd("%server.name%", () => g == null ? "DM" : g.Name);
_reps.TryAdd("%server.members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server.time%", () =>
{
TimeZoneInfo to = TimeZoneInfo.Local;
if (g != null)
{
if (GuildTimezoneService.AllServices.TryGetValue(client.CurrentUser.Id, out var tz))
to = tz.GetTimeZoneOrDefault(g.Id) ?? TimeZoneInfo.Local;
}
return TimeZoneInfo.ConvertTime(DateTime.UtcNow,
TimeZoneInfo.Utc,
to).ToString("HH:mm ") + to.StandardName.GetInitials();
});
return this;
}
public ReplacementBuilder WithChannel(IMessageChannel ch)
{
/*OBSOLETE*/
_reps.TryAdd("%channel%", () => (ch as ITextChannel)?.Mention ?? "#" + ch.Name);
_reps.TryAdd("%chname%", () => ch.Name);
_reps.TryAdd("%cid%", () => ch?.Id.ToString());
/*NEW*/
_reps.TryAdd("%channel.mention%", () => (ch as ITextChannel)?.Mention ?? "#" + ch.Name);
_reps.TryAdd("%channel.name%", () => ch.Name);
_reps.TryAdd("%channel.id%", () => ch.Id.ToString());
_reps.TryAdd("%channel.created%", () => ch.CreatedAt.ToString("HH:mm MM.dd.yyyy"));
_reps.TryAdd("%channel.nsfw%", () => (ch as ITextChannel)?.IsNsfw.ToString() ?? "-");
_reps.TryAdd("%channel.topic%", () => (ch as ITextChannel)?.Topic ?? "-");
return this;
}
public ReplacementBuilder WithUser(IUser user)
{
// /*OBSOLETE*/
// _reps.TryAdd("%user%", () => user.Mention);
// _reps.TryAdd("%userfull%", () => user.ToString());
// _reps.TryAdd("%username%", () => user.Username);
// _reps.TryAdd("%userdiscrim%", () => user.Discriminator);
// _reps.TryAdd("%useravatar%", () => user.RealAvatarUrl()?.ToString());
// _reps.TryAdd("%id%", () => user.Id.ToString());
// _reps.TryAdd("%uid%", () => user.Id.ToString());
// /*NEW*/
// _reps.TryAdd("%user.mention%", () => user.Mention);
// _reps.TryAdd("%user.fullname%", () => user.ToString());
// _reps.TryAdd("%user.name%", () => user.Username);
// _reps.TryAdd("%user.discrim%", () => user.Discriminator);
// _reps.TryAdd("%user.avatar%", () => user.RealAvatarUrl()?.ToString());
// _reps.TryAdd("%user.id%", () => user.Id.ToString());
// _reps.TryAdd("%user.created_time%", () => user.CreatedAt.ToString("HH:mm"));
// _reps.TryAdd("%user.created_date%", () => user.CreatedAt.ToString("dd.MM.yyyy"));
// _reps.TryAdd("%user.joined_time%", () => (user as IGuildUser)?.JoinedAt?.ToString("HH:mm") ?? "-");
// _reps.TryAdd("%user.joined_date%", () => (user as IGuildUser)?.JoinedAt?.ToString("dd.MM.yyyy") ?? "-");
WithManyUsers(new[] { user });
return this;
}
public ReplacementBuilder WithManyUsers(IEnumerable<IUser> users)
{
/*OBSOLETE*/
_reps.TryAdd("%user%", () => string.Join(" ", users.Select(user => user.Mention)));
_reps.TryAdd("%userfull%", () => string.Join(" ", users.Select(user => user.ToString())));
_reps.TryAdd("%username%", () => string.Join(" ", users.Select(user => user.Username)));
_reps.TryAdd("%userdiscrim%", () => string.Join(" ", users.Select(user => user.Discriminator)));
_reps.TryAdd("%useravatar%", () => string.Join(" ", users.Select(user => user.RealAvatarUrl()?.ToString())));
_reps.TryAdd("%id%", () => string.Join(" ", users.Select(user => user.Id.ToString())));
_reps.TryAdd("%uid%", () => string.Join(" ", users.Select(user => user.Id.ToString())));
/*NEW*/
_reps.TryAdd("%user.mention%", () => string.Join(" ", users.Select(user => user.Mention)));
_reps.TryAdd("%user.fullname%", () => string.Join(" ", users.Select(user => user.ToString())));
_reps.TryAdd("%user.name%", () => string.Join(" ", users.Select(user => user.Username)));
_reps.TryAdd("%user.discrim%", () => string.Join(" ", users.Select(user => user.Discriminator)));
_reps.TryAdd("%user.avatar%", () => string.Join(" ", users.Select(user => user.RealAvatarUrl()?.ToString())));
_reps.TryAdd("%user.id%", () => string.Join(" ", users.Select(user => user.Id.ToString())));
_reps.TryAdd("%user.created_time%", () => string.Join(" ", users.Select(user => user.CreatedAt.ToString("HH:mm"))));
_reps.TryAdd("%user.created_date%", () => string.Join(" ", users.Select(user => user.CreatedAt.ToString("dd.MM.yyyy"))));
_reps.TryAdd("%user.joined_time%", () => string.Join(" ", users.Select(user => (user as IGuildUser)?.JoinedAt?.ToString("HH:mm") ?? "-")));
_reps.TryAdd("%user.joined_date%", () => string.Join(" ", users.Select(user => (user as IGuildUser)?.JoinedAt?.ToString("dd.MM.yyyy") ?? "-")));
return this;
}
private ReplacementBuilder WithStats(DiscordSocketClient c)
{
/*OBSOLETE*/
_reps.TryAdd("%servers%", () => c.Guilds.Count.ToString());
_reps.TryAdd("%users%", () => c.Guilds.Sum(s => s.Users.Count).ToString());
/*NEW*/
_reps.TryAdd("%shard.servercount%", () => c.Guilds.Count.ToString());
_reps.TryAdd("%shard.usercount%", () => c.Guilds.Sum(s => s.Users.Count).ToString());
_reps.TryAdd("%shard.id%", () => c.ShardId.ToString());
return this;
}
// public ReplacementBuilder WithMusic(MusicService ms)
// {
// _reps.TryAdd("%playing%", () =>
// {
// var cnt = ms.MusicPlayers.Count(kvp => kvp.Value.Current.Current != null);
// if (cnt != 1) return cnt.ToString();
// try
// {
// var mp = ms.MusicPlayers.FirstOrDefault();
// var title = mp.Value?.Current.Current?.Title;
// return title ?? "No songs";
// }
// catch
// {
// return "error";
// }
// });
// _reps.TryAdd("%queued%", () => ms.MusicPlayers.Sum(kvp => kvp.Value.QueueArray().Songs.Length).ToString());
//
// _reps.TryAdd("%music.queued%", () => ms.MusicPlayers.Sum(kvp => kvp.Value.QueueArray().Songs.Length).ToString());
// _reps.TryAdd("%music.playing%", () =>
// {
// var cnt = ms.MusicPlayers.Count(kvp => kvp.Value.Current.Current != null);
// if (cnt != 1) return cnt.ToString();
// try
// {
// var mp = ms.MusicPlayers.FirstOrDefault();
// var title = mp.Value?.Current.Current?.Title;
// return title ?? "No songs";
// }
// catch
// {
// return "error";
// }
// });
// return this;
// }
public ReplacementBuilder WithRngRegex()
{
var rng = new WizBotRandom();
_regex.TryAdd(rngRegex, (match) =>
{
if (!int.TryParse(match.Groups["from"].ToString(), out var from))
from = 0;
if (!int.TryParse(match.Groups["to"].ToString(), out var to))
to = 0;
if (from == 0 && to == 0)
return rng.Next(0, 11).ToString();
if (from >= to)
return string.Empty;
return rng.Next(from, to + 1).ToString();
});
return this;
}
public ReplacementBuilder WithOverride(string key, Func<string> output)
{
_reps.AddOrUpdate(key, output, delegate { return output; });
return this;
}
public Replacer Build()
{
return new Replacer(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray());
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace WizBot.Common.Replacements
{
public class Replacer
{
private readonly IEnumerable<(string Key, Func<string> Text)> _replacements;
private readonly IEnumerable<(Regex Regex, Func<Match, string> Replacement)> _regex;
public Replacer(IEnumerable<(string, Func<string>)> replacements, IEnumerable<(Regex, Func<Match, string>)> regex)
{
_replacements = replacements;
_regex = regex;
}
public string Replace(string input)
{
if (string.IsNullOrWhiteSpace(input))
return input;
foreach (var (Key, Text) in _replacements)
{
if (input.Contains(Key))
input = input.Replace(Key, Text(), StringComparison.InvariantCulture);
}
foreach (var item in _regex)
{
input = item.Regex.Replace(input, (m) => item.Replacement(m));
}
return input;
}
public void Replace(CREmbed embedData)
{
embedData.PlainText = Replace(embedData.PlainText);
embedData.Description = Replace(embedData.Description);
embedData.Title = Replace(embedData.Title);
embedData.Thumbnail = Replace(embedData.Thumbnail);
embedData.Image = Replace(embedData.Image);
if (embedData.Author != null)
{
embedData.Author.Name = Replace(embedData.Author.Name);
embedData.Author.IconUrl = Replace(embedData.Author.IconUrl);
}
if (embedData.Fields != null)
foreach (var f in embedData.Fields)
{
f.Name = Replace(f.Name);
f.Value = Replace(f.Value);
}
if (embedData.Footer != null)
{
embedData.Footer.Text = Replace(embedData.Footer.Text);
embedData.Footer.IconUrl = Replace(embedData.Footer.IconUrl);
}
}
}
}

View File

@ -0,0 +1,16 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
namespace WizBot.Common
{
public class RequireObjectPropertiesContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
contract.ItemRequired = Required.DisallowNull;
return contract;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using Discord;
namespace WizBot.Common.ShardCom
{
public class ShardComMessage
{
public int ShardId { get; set; }
public ConnectionState ConnectionState { get; set; }
public int Guilds { get; set; }
public DateTime Time { get; set; }
public ShardComMessage Clone() =>
new ShardComMessage
{
ShardId = ShardId,
ConnectionState = ConnectionState,
Guilds = Guilds,
Time = Time,
};
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WizBot.Core.Services;
namespace WizBot.Common.ShardCom
{
public class ShardComServer
{
private readonly IDataCache _cache;
public ShardComServer(IDataCache cache)
{
_cache = cache;
}
public void Start()
{
var sub = _cache.Redis.GetSubscriber();
sub.SubscribeAsync("shardcoord_send", (ch, data) =>
{
var _ = OnDataReceived(JsonConvert.DeserializeObject<ShardComMessage>(data));
}, StackExchange.Redis.CommandFlags.FireAndForget);
}
public event Func<ShardComMessage, Task> OnDataReceived = delegate { return Task.CompletedTask; };
}
}

View File

@ -0,0 +1,63 @@
using System;
namespace WizBot.Core.Common
{
public struct ShmartNumber : IEquatable<ShmartNumber>
{
public long Value { get; }
public string Input { get; }
public ShmartNumber(long val, string input = null)
{
Value = val;
Input = input;
}
public static implicit operator ShmartNumber(long num)
{
return new ShmartNumber(num);
}
public static implicit operator long(ShmartNumber num)
{
return num.Value;
}
public static implicit operator ShmartNumber(int num)
{
return new ShmartNumber(num);
}
public override string ToString()
{
return Value.ToString();
}
public override bool Equals(object obj)
{
return obj is ShmartNumber sn
? Equals(sn)
: false;
}
public bool Equals(ShmartNumber other)
{
return other.Value == Value;
}
public override int GetHashCode()
{
return Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture);
}
public static bool operator ==(ShmartNumber left, ShmartNumber right)
{
return left.Equals(right);
}
public static bool operator !=(ShmartNumber left, ShmartNumber right)
{
return !(left == right);
}
}
}

View File

@ -0,0 +1,91 @@
using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
namespace WizBot.Common
{
public sealed class ReactionEventWrapper : IDisposable
{
public IUserMessage Message { get; }
public event Action<SocketReaction> OnReactionAdded = delegate { };
public event Action<SocketReaction> OnReactionRemoved = delegate { };
public event Action OnReactionsCleared = delegate { };
public ReactionEventWrapper(DiscordSocketClient client, IUserMessage msg)
{
Message = msg ?? throw new ArgumentNullException(nameof(msg));
_client = client;
_client.ReactionAdded += Discord_ReactionAdded;
_client.ReactionRemoved += Discord_ReactionRemoved;
_client.ReactionsCleared += Discord_ReactionsCleared;
}
private Task Discord_ReactionsCleared(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel)
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionsCleared?.Invoke();
}
catch { }
});
return Task.CompletedTask;
}
private Task Discord_ReactionRemoved(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionRemoved?.Invoke(reaction);
}
catch { }
});
return Task.CompletedTask;
}
private Task Discord_ReactionAdded(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionAdded?.Invoke(reaction);
}
catch { }
});
return Task.CompletedTask;
}
public void UnsubAll()
{
_client.ReactionAdded -= Discord_ReactionAdded;
_client.ReactionRemoved -= Discord_ReactionRemoved;
_client.ReactionsCleared -= Discord_ReactionsCleared;
OnReactionAdded = null;
OnReactionRemoved = null;
OnReactionsCleared = null;
}
private bool disposing = false;
private readonly DiscordSocketClient _client;
public void Dispose()
{
if (disposing)
return;
disposing = true;
UnsubAll();
}
}
}

View File

@ -0,0 +1,9 @@
namespace WizBot.Common.TypeReaders
{
public enum AddRemove
{
Add = 0,
Rem = 1,
Rm = 1,
}
}

View File

@ -0,0 +1,87 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using WizBot.Core.Services;
using WizBot.Modules.CustomReactions.Services;
using WizBot.Core.Common.TypeReaders;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
namespace WizBot.Common.TypeReaders
{
public class CommandTypeReader : WizBotTypeReader<CommandInfo>
{
public CommandTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
var _cmds = services.GetService<CommandService>();
var _cmdHandler = services.GetService<CommandHandler>();
input = input.ToUpperInvariant();
var prefix = _cmdHandler.GetPrefix(context.Guild);
if (!input.StartsWith(prefix.ToUpperInvariant(), StringComparison.InvariantCulture))
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found."));
input = input.Substring(prefix.Length);
var cmd = _cmds.Commands.FirstOrDefault(c =>
c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input));
if (cmd == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found."));
return Task.FromResult(TypeReaderResult.FromSuccess(cmd));
}
}
public class CommandOrCrTypeReader : WizBotTypeReader<CommandOrCrInfo>
{
private readonly DiscordSocketClient _client;
private readonly CommandService _cmds;
public CommandOrCrTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
_client = client;
_cmds = cmds;
}
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
input = input.ToUpperInvariant();
var _crs = services.GetService<CustomReactionsService>();
if (_crs.ReactionExists(context.Guild?.Id, input))
{
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input, CommandOrCrInfo.Type.Custom));
}
var cmd = await new CommandTypeReader(_client, _cmds).ReadAsync(context, input, services).ConfigureAwait(false);
if (cmd.IsSuccess)
{
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name, CommandOrCrInfo.Type.Normal));
}
return TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found.");
}
}
public class CommandOrCrInfo
{
public enum Type
{
Normal,
Custom,
}
public string Name { get; set; }
public Type CmdType { get; set; }
public bool IsCustom => CmdType == Type.Custom;
public CommandOrCrInfo(string input, Type type)
{
this.Name = input;
this.CmdType = type;
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using WizBot.Modules.Administration.Services;
using WizBot.Core.Common.TypeReaders;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
namespace WizBot.Common.TypeReaders
{
public class GuildDateTimeTypeReader : WizBotTypeReader<GuildDateTime>
{
public GuildDateTimeTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
var gdt = Parse(services, context.Guild.Id, input);
if(gdt == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input string is in an incorrect format."));
return Task.FromResult(TypeReaderResult.FromSuccess(gdt));
}
public static GuildDateTime Parse(IServiceProvider services, ulong guildId, string input)
{
var _gts = services.GetService<GuildTimezoneService>();
if (!DateTime.TryParse(input, out var dt))
return null;
var tz = _gts.GetTimeZoneOrUtc(guildId);
return new GuildDateTime(tz, dt);
}
}
public class GuildDateTime
{
public TimeZoneInfo Timezone { get; }
public DateTime CurrentGuildTime { get; }
public DateTime InputTime { get; }
public DateTime InputTimeUtc { get; }
private GuildDateTime() { }
public GuildDateTime(TimeZoneInfo guildTimezone, DateTime inputTime)
{
var now = DateTime.UtcNow;
Timezone = guildTimezone;
CurrentGuildTime = TimeZoneInfo.ConvertTime(now, TimeZoneInfo.Utc, Timezone);
InputTime = inputTime;
InputTimeUtc = TimeZoneInfo.ConvertTime(inputTime, Timezone, TimeZoneInfo.Utc);
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Core.Common.TypeReaders;
using Discord;
namespace WizBot.Common.TypeReaders
{
public class GuildTypeReader : WizBotTypeReader<IGuild>
{
private readonly DiscordSocketClient _client;
public GuildTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
_client = client;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider _)
{
input = input.Trim().ToUpperInvariant();
var guilds = _client.Guilds;
var guild = guilds.FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == input) ?? //by id
guilds.FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == input); //by name
if (guild != null)
return Task.FromResult(TypeReaderResult.FromSuccess(guild));
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No guild by that name or Id found"));
}
}
}

View File

@ -0,0 +1,27 @@
namespace WizBot.Common.TypeReaders.Models
{
public class PermissionAction
{
public static PermissionAction Enable => new PermissionAction(true);
public static PermissionAction Disable => new PermissionAction(false);
public bool Value { get; }
public PermissionAction(bool value)
{
this.Value = value;
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return this.Value == ((PermissionAction)obj).Value;
}
public override int GetHashCode() => Value.GetHashCode();
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace WizBot.Core.Common.TypeReaders.Models
{
public class StoopidTime
{
public string Input { get; set; }
public TimeSpan Time { get; set; }
private static readonly Regex _regex = new Regex(
@"^(?:(?<months>\d)mo)?(?:(?<weeks>\d{1,2})w)?(?:(?<days>\d{1,2})d)?(?:(?<hours>\d{1,4})h)?(?:(?<minutes>\d{1,5})m)?(?:(?<seconds>\d{1,6})s)?$",
RegexOptions.Compiled | RegexOptions.Multiline);
private StoopidTime() { }
public static StoopidTime FromInput(string input)
{
var m = _regex.Match(input);
if (m.Length == 0)
{
throw new ArgumentException("Invalid string input format.");
}
string output = "";
var namesAndValues = new Dictionary<string, int>();
foreach (var groupName in _regex.GetGroupNames())
{
if (groupName == "0") continue;
if (!int.TryParse(m.Groups[groupName].Value, out var value))
{
namesAndValues[groupName] = 0;
continue;
}
if (value < 1)
{
throw new ArgumentException($"Invalid {groupName} value.");
}
namesAndValues[groupName] = value;
output += m.Groups[groupName].Value + " " + groupName + " ";
}
var ts = new TimeSpan(30 * namesAndValues["months"] +
7 * namesAndValues["weeks"] +
namesAndValues["days"],
namesAndValues["hours"],
namesAndValues["minutes"],
namesAndValues["seconds"]);
if (ts > TimeSpan.FromDays(90))
{
throw new ArgumentException("Time is too long.");
}
return new StoopidTime()
{
Input = input,
Time = ts,
};
}
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using WizBot.Extensions;
using WizBot.Core.Common.TypeReaders;
using Discord.WebSocket;
namespace WizBot.Common.TypeReaders
{
public class ModuleTypeReader : WizBotTypeReader<ModuleInfo>
{
private readonly CommandService _cmds;
public ModuleTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
_cmds = cmds;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider _)
{
input = input.ToUpperInvariant();
var module = _cmds.Modules.GroupBy(m => m.GetTopLevelModule()).FirstOrDefault(m => m.Key.Name.ToUpperInvariant() == input)?.Key;
if (module == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such module found."));
return Task.FromResult(TypeReaderResult.FromSuccess(module));
}
}
public class ModuleOrCrTypeReader : WizBotTypeReader<ModuleOrCrInfo>
{
private readonly CommandService _cmds;
public ModuleOrCrTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
_cmds = cmds;
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider _)
{
input = input.ToUpperInvariant();
var module = _cmds.Modules.GroupBy(m => m.GetTopLevelModule()).FirstOrDefault(m => m.Key.Name.ToUpperInvariant() == input)?.Key;
if (module == null && input != "ACTUALCUSTOMREACTIONS")
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such module found."));
return Task.FromResult(TypeReaderResult.FromSuccess(new ModuleOrCrInfo
{
Name = input,
}));
}
}
public class ModuleOrCrInfo
{
public string Name { get; set; }
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Common.TypeReaders.Models;
using WizBot.Core.Common.TypeReaders;
namespace WizBot.Common.TypeReaders
{
/// <summary>
/// Used instead of bool for more flexible keywords for true/false only in the permission module
/// </summary>
public class PermissionActionTypeReader : WizBotTypeReader<PermissionAction>
{
public PermissionActionTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider _)
{
input = input.ToUpperInvariant();
switch (input)
{
case "1":
case "T":
case "TRUE":
case "ENABLE":
case "ENABLED":
case "ALLOW":
case "PERMIT":
case "UNBAN":
return Task.FromResult(TypeReaderResult.FromSuccess(PermissionAction.Enable));
case "0":
case "F":
case "FALSE":
case "DENY":
case "DISABLE":
case "DISABLED":
case "DISALLOW":
case "BAN":
return Task.FromResult(TypeReaderResult.FromSuccess(PermissionAction.Disable));
default:
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Did not receive a valid boolean value"));
}
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using SixLabors.ImageSharp;
namespace WizBot.Core.Common.TypeReaders
{
public class Rgba32TypeReader : WizBotTypeReader<Color>
{
public Rgba32TypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
await Task.Yield();
input = input.Replace("#", "", StringComparison.InvariantCulture);
try
{
return TypeReaderResult.FromSuccess(Color.ParseHex(input));
}
catch
{
return TypeReaderResult.FromError(CommandError.ParseFailed, "Parameter is not a valid color hex.");
}
}
}
}

View File

@ -0,0 +1,109 @@
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using WizBot.Core.Services;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WizBot.Core.Modules.Gambling.Services;
namespace WizBot.Core.Common.TypeReaders
{
public class ShmartNumberTypeReader : WizBotTypeReader<ShmartNumber>
{
public ShmartNumberTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
await Task.Yield();
if (string.IsNullOrWhiteSpace(input))
return TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty.");
var i = input.Trim().ToUpperInvariant();
i = i.Replace("K", "000");
//can't add m because it will conflict with max atm
if (TryHandlePercentage(services, context, i, out var num))
return TypeReaderResult.FromSuccess(new ShmartNumber(num, i));
try
{
var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services);
var lon = (long)(decimal.Parse(expr.Evaluate().ToString()));
return TypeReaderResult.FromSuccess(new ShmartNumber(lon, input));
}
catch (Exception)
{
return TypeReaderResult.FromError(CommandError.ParseFailed, $"Invalid input: {input}");
}
}
private static void EvaluateParam(string name, NCalc.ParameterArgs args, ICommandContext ctx, IServiceProvider svc)
{
switch (name.ToUpperInvariant())
{
case "PI":
args.Result = Math.PI;
break;
case "E":
args.Result = Math.E;
break;
case "ALL":
case "ALLIN":
args.Result = Cur(svc, ctx);
break;
case "HALF":
args.Result = Cur(svc, ctx) / 2;
break;
case "MAX":
args.Result = Max(svc, ctx);
break;
default:
break;
}
}
private static readonly Regex percentRegex = new Regex(@"^((?<num>100|\d{1,2})%)$", RegexOptions.Compiled);
private static long Cur(IServiceProvider services, ICommandContext ctx)
{
var _db = services.GetService<DbService>();
long cur;
using (var uow = _db.GetDbContext())
{
cur = uow.DiscordUsers.GetUserCurrency(ctx.User.Id);
uow.SaveChanges();
}
return cur;
}
private static long Max(IServiceProvider services, ICommandContext ctx)
{
var settings = services.GetService<GamblingConfigService>().Data;
var max = settings.MaxBet;
return max == 0
? Cur(services, ctx)
: max;
}
private static bool TryHandlePercentage(IServiceProvider services, ICommandContext ctx, string input, out long num)
{
num = 0;
var m = percentRegex.Match(input);
if (m.Captures.Count != 0)
{
if (!long.TryParse(m.Groups["num"].ToString(), out var percent))
return false;
num = (long)(Cur(services, ctx) * (percent / 100.0f));
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,30 @@
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Core.Common.TypeReaders.Models;
using System;
using System.Threading.Tasks;
namespace WizBot.Core.Common.TypeReaders
{
public class StoopidTimeTypeReader : WizBotTypeReader<StoopidTime>
{
public StoopidTimeTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds)
{
}
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
if (string.IsNullOrWhiteSpace(input))
return Task.FromResult(TypeReaderResult.FromError(CommandError.Unsuccessful, "Input is empty."));
try
{
var time = StoopidTime.FromInput(input);
return Task.FromResult(TypeReaderResult.FromSuccess(time));
}
catch (Exception ex)
{
return Task.FromResult(TypeReaderResult.FromError(CommandError.Exception, ex.Message));
}
}
}
}

View File

@ -0,0 +1,18 @@
using Discord.Commands;
using Discord.WebSocket;
namespace WizBot.Core.Common.TypeReaders
{
public abstract class WizBotTypeReader<T> : TypeReader
{
private readonly DiscordSocketClient _client;
private readonly CommandService _cmds;
private WizBotTypeReader() { }
protected WizBotTypeReader(DiscordSocketClient client, CommandService cmds)
{
_client = client;
_cmds = cmds;
}
}
}

View File

@ -0,0 +1,149 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using WizBot.Core.Services;
using WizBot.Extensions;
using System.Globalization;
using System.Threading.Tasks;
namespace WizBot.Modules
{
public abstract class WizBotModule : ModuleBase
{
protected CultureInfo _cultureInfo { get; set; }
public IBotStrings Strings { get; set; }
public CommandHandler CmdHandler { get; set; }
public ILocalization Localization { get; set; }
public string Prefix => CmdHandler.GetPrefix(ctx.Guild);
protected ICommandContext ctx => Context;
protected WizBotModule()
{
}
protected override void BeforeExecute(CommandInfo cmd)
{
_cultureInfo = Localization.GetCultureInfo(ctx.Guild?.Id);
}
protected string GetText(string key) =>
Strings.GetText(key, _cultureInfo);
protected string GetText(string key, params object[] args) =>
Strings.GetText(key, _cultureInfo, args);
public Task<IUserMessage> ErrorLocalizedAsync(string textKey, params object[] args)
{
var text = GetText(textKey, args);
return ctx.Channel.SendErrorAsync(text);
}
public Task<IUserMessage> ReplyErrorLocalizedAsync(string textKey, params object[] args)
{
var text = GetText(textKey, args);
return ctx.Channel.SendErrorAsync(Format.Bold(ctx.User.ToString()) + " " + text);
}
public Task<IUserMessage> ConfirmLocalizedAsync(string textKey, params object[] args)
{
var text = GetText(textKey, args);
return ctx.Channel.SendConfirmAsync(text);
}
public Task<IUserMessage> ReplyConfirmLocalizedAsync(string textKey, params object[] args)
{
var text = GetText(textKey, args);
return ctx.Channel.SendConfirmAsync(Format.Bold(ctx.User.ToString()) + " " + text);
}
public async Task<bool> PromptUserConfirmAsync(EmbedBuilder embed)
{
embed.WithOkColor()
.WithFooter("yes/no");
var msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
try
{
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id).ConfigureAwait(false);
input = input?.ToUpperInvariant();
if (input != "YES" && input != "Y")
{
return false;
}
return true;
}
finally
{
var _ = Task.Run(() => msg.DeleteAsync());
}
}
// TypeConverter typeConverter = TypeDescriptor.GetConverter(propType); ?
public async Task<string> GetUserInputAsync(ulong userId, ulong channelId)
{
var userInputTask = new TaskCompletionSource<string>();
var dsc = (DiscordSocketClient)ctx.Client;
try
{
dsc.MessageReceived += MessageReceived;
if ((await Task.WhenAny(userInputTask.Task, Task.Delay(10000)).ConfigureAwait(false)) != userInputTask.Task)
{
return null;
}
return await userInputTask.Task.ConfigureAwait(false);
}
finally
{
dsc.MessageReceived -= MessageReceived;
}
Task MessageReceived(SocketMessage arg)
{
var _ = Task.Run(() =>
{
if (!(arg is SocketUserMessage userMsg) ||
!(userMsg.Channel is ITextChannel chan) ||
userMsg.Author.Id != userId ||
userMsg.Channel.Id != channelId)
{
return Task.CompletedTask;
}
if (userInputTask.TrySetResult(arg.Content))
{
userMsg.DeleteAfter(1);
}
return Task.CompletedTask;
});
return Task.CompletedTask;
}
}
}
public abstract class WizBotModule<TService> : WizBotModule
{
public TService _service { get; set; }
protected WizBotModule() : base()
{
}
}
public abstract class WizBotSubmodule : WizBotModule
{
protected WizBotSubmodule() : base() { }
}
public abstract class WizBotSubmodule<TService> : WizBotModule<TService> where TService : INService
{
protected WizBotSubmodule() : base()
{
}
}
}

View File

@ -0,0 +1,7 @@
namespace WizBot.Modules
{
public static class WizBotModuleExtensions
{
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Security.Cryptography;
namespace WizBot.Common
{
public class WizBotRandom : Random
{
readonly RandomNumberGenerator _rng;
public WizBotRandom() : base()
{
_rng = RandomNumberGenerator.Create();
}
public override int Next()
{
var bytes = new byte[sizeof(int)];
_rng.GetBytes(bytes);
return Math.Abs(BitConverter.ToInt32(bytes, 0));
}
public override int Next(int maxValue)
{
if (maxValue <= 0)
throw new ArgumentOutOfRangeException(nameof(maxValue));
var bytes = new byte[sizeof(int)];
_rng.GetBytes(bytes);
return Math.Abs(BitConverter.ToInt32(bytes, 0)) % maxValue;
}
public override int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
throw new ArgumentOutOfRangeException(nameof(maxValue));
if (minValue == maxValue)
return minValue;
var bytes = new byte[sizeof(int)];
_rng.GetBytes(bytes);
var sign = Math.Sign(BitConverter.ToInt32(bytes, 0));
return (sign * BitConverter.ToInt32(bytes, 0)) % (maxValue - minValue) + minValue;
}
public long NextLong(long minValue, long maxValue)
{
if (minValue > maxValue)
throw new ArgumentOutOfRangeException(nameof(maxValue));
if (minValue == maxValue)
return minValue;
var bytes = new byte[sizeof(long)];
_rng.GetBytes(bytes);
var sign = Math.Sign(BitConverter.ToInt64(bytes, 0));
return (sign * BitConverter.ToInt64(bytes, 0)) % (maxValue - minValue) + minValue;
}
public override void NextBytes(byte[] buffer)
{
_rng.GetBytes(buffer);
}
protected override double Sample()
{
var bytes = new byte[sizeof(double)];
_rng.GetBytes(bytes);
return Math.Abs(BitConverter.ToDouble(bytes, 0) / double.MaxValue + 1);
}
public override double NextDouble()
{
var bytes = new byte[sizeof(double)];
_rng.GetBytes(bytes);
return BitConverter.ToDouble(bytes, 0);
}
}
}

View File

@ -0,0 +1,14 @@
using System;
namespace WizBot.Common.Yml
{
public class CommentAttribute : Attribute
{
public string Comment { get; }
public CommentAttribute(string comment)
{
Comment = comment;
}
}
}

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.TypeInspectors;
namespace WizBot.Common.Yml
{
public class CommentGatheringTypeInspector : TypeInspectorSkeleton
{
private readonly ITypeInspector innerTypeDescriptor;
public CommentGatheringTypeInspector(ITypeInspector innerTypeDescriptor)
{
this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
}
public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
{
return innerTypeDescriptor
.GetProperties(type, container)
.Select(d => new CommentsPropertyDescriptor(d));
}
private sealed class CommentsPropertyDescriptor : IPropertyDescriptor
{
private readonly IPropertyDescriptor baseDescriptor;
public CommentsPropertyDescriptor(IPropertyDescriptor baseDescriptor)
{
this.baseDescriptor = baseDescriptor;
Name = baseDescriptor.Name;
}
public string Name { get; set; }
public Type Type { get { return baseDescriptor.Type; } }
public Type TypeOverride
{
get { return baseDescriptor.TypeOverride; }
set { baseDescriptor.TypeOverride = value; }
}
public int Order { get; set; }
public ScalarStyle ScalarStyle
{
get { return baseDescriptor.ScalarStyle; }
set { baseDescriptor.ScalarStyle = value; }
}
public bool CanWrite { get { return baseDescriptor.CanWrite; } }
public void Write(object target, object value)
{
baseDescriptor.Write(target, value);
}
public T GetCustomAttribute<T>() where T : Attribute
{
return baseDescriptor.GetCustomAttribute<T>();
}
public IObjectDescriptor Read(object target)
{
var comment = baseDescriptor.GetCustomAttribute<CommentAttribute>();
return comment != null
? new CommentsObjectDescriptor(baseDescriptor.Read(target), comment.Comment)
: baseDescriptor.Read(target);
}
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
namespace WizBot.Common.Yml
{
public sealed class CommentsObjectDescriptor : IObjectDescriptor
{
private readonly IObjectDescriptor innerDescriptor;
public CommentsObjectDescriptor(IObjectDescriptor innerDescriptor, string comment)
{
this.innerDescriptor = innerDescriptor;
this.Comment = comment;
}
public string Comment { get; private set; }
public object Value { get { return innerDescriptor.Value; } }
public Type Type { get { return innerDescriptor.Type; } }
public Type StaticType { get { return innerDescriptor.StaticType; } }
public ScalarStyle ScalarStyle { get { return innerDescriptor.ScalarStyle; } }
}
}

View File

@ -0,0 +1,26 @@
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.ObjectGraphVisitors;
namespace WizBot.Common.Yml
{
public class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor
{
public CommentsObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor)
: base(nextVisitor)
{
}
public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context)
{
var commentsDescriptor = value as CommentsObjectDescriptor;
if (commentsDescriptor != null && !string.IsNullOrWhiteSpace(commentsDescriptor.Comment))
{
context.Emit(new Comment(commentsDescriptor.Comment.Replace("\n", "\n# "), false));
}
return base.EnterMapping(key, value, context);
}
}
}

View File

@ -0,0 +1,32 @@
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.EventEmitters;
namespace WizBot.Common.Yml
{
public class MultilineScalarFlowStyleEmitter : ChainedEventEmitter
{
public MultilineScalarFlowStyleEmitter(IEventEmitter nextEmitter)
: base(nextEmitter) { }
public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
{
if (typeof(string).IsAssignableFrom(eventInfo.Source.Type))
{
string value = eventInfo.Source.Value as string;
if (!string.IsNullOrEmpty(value))
{
bool isMultiLine = value.IndexOfAny(new char[] { '\r', '\n', '\x85', '\x2028', '\x2029' }) >= 0;
if (isMultiLine)
eventInfo = new ScalarEventInfo(eventInfo.Source)
{
Style = ScalarStyle.Literal,
};
}
}
nextEmitter.Emit(eventInfo, emitter);
}
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Globalization;
using SixLabors.ImageSharp.PixelFormats;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace WizBot.Common.Yml
{
public class Rgba32Converter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(Rgba32);
}
public object ReadYaml(IParser parser, Type type)
{
var scalar = parser.Consume<Scalar>();
var result = Rgba32.ParseHex(scalar.Value);
return result;
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
var color = (Rgba32)value;
var val = (uint)(color.B << 0 | color.G << 8 | color.R << 16);
emitter.Emit(new Scalar(val.ToString("X6").ToLower()));
}
}
public class CultureInfoConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(CultureInfo);
}
public object ReadYaml(IParser parser, Type type)
{
var scalar = parser.Consume<Scalar>();
var result = new CultureInfo(scalar.Value);
return result;
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
var ci = (CultureInfo)value;
emitter.Emit(new Scalar(ci.Name));
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace WizBot.Common.Yml
{
public class UriConverter : IYamlTypeConverter
{
public bool Accepts(Type type)
{
return type == typeof(Uri);
}
public object ReadYaml(IParser parser, Type type)
{
var scalar = parser.Consume<Scalar>();
var result = new Uri(scalar.Value);
return result;
}
public void WriteYaml(IEmitter emitter, object value, Type type)
{
var uri = (Uri)value;
emitter.Emit(new Scalar(uri.ToString()));
}
}
}

View File

@ -0,0 +1,25 @@
using YamlDotNet.Serialization;
namespace WizBot.Common.Yml
{
public class Yaml
{
public static ISerializer Serializer => new SerializerBuilder()
.WithTypeInspector(inner => new CommentGatheringTypeInspector(inner))
.WithEmissionPhaseObjectGraphVisitor(args => new CommentsObjectGraphVisitor(args.InnerVisitor))
.WithEventEmitter(args => new MultilineScalarFlowStyleEmitter(args))
.WithNamingConvention(YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention.Instance)
.WithIndentedSequences()
.WithTypeConverter(new Rgba32Converter())
.WithTypeConverter(new CultureInfoConverter())
.WithTypeConverter(new UriConverter())
.Build();
public static IDeserializer Deserializer => new DeserializerBuilder()
.WithNamingConvention(YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention.Instance)
.WithTypeConverter(new Rgba32Converter())
.WithTypeConverter(new CultureInfoConverter())
.WithTypeConverter(new UriConverter())
.Build();
}
}

View File

@ -0,0 +1,58 @@
namespace WizBot.Common.Yml
{
public class YamlHelper
{
// https://github.com/aaubry/YamlDotNet/blob/0f4cc205e8b2dd8ef6589d96de32bf608a687c6f/YamlDotNet/Core/Scanner.cs#L1687
/// <summary>
/// This is modified code from yamldotnet's repo which handles parsing unicode code points
/// it is needed as yamldotnet doesn't support unescaped unicode characters
/// </summary>
/// <param name="point">Unicode code point</param>
/// <returns>Actual character</returns>
public static string UnescapeUnicodeCodePoint(string point)
{
var character = 0;
// Scan the character value.
foreach (var c in point)
{
if (!IsHex(c))
{
return point;
}
character = (character << 4) + AsHex(c);
}
// Check the value and write the character.
if (character >= 0xD800 && character <= 0xDFFF || character > 0x10FFFF)
{
return point;
}
return char.ConvertFromUtf32(character);
}
public static bool IsHex(char c)
{
return
(c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f');
}
public static int AsHex(char c)
{
if (c <= '9')
{
return c - '0';
}
if (c <= 'F')
{
return c - 'A' + 10;
}
return c - 'a' + 10;
}
}
}

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