Compare commits

..

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

1550 changed files with 102095 additions and 83056 deletions

View File

@ -1,16 +1,14 @@
# Ignore all files
*
# Use NadekoBot project
!src/NadekoBot/**
# Use NadekoBot.Coordinator project
!src/NadekoBot.Coordinator/**
# Use Generators project
!src/NadekoBot.Generators/**
# Use Ayu stuff
!src/ayu/**
# 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/**/obj/*
src/NadekoBot/data/creds.yml

208
.editorconfig Normal file
View File

@ -0,0 +1,208 @@
[*]
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

171
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,171 @@
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

36
.github/workflows/mkdocs-deploy.yml vendored Normal file
View File

@ -0,0 +1,36 @@
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

37
.gitignore vendored
View File

@ -1,18 +1,18 @@
#Manually added files
command_errors*.txt
src/WizBot/data/last_known_version.txt
# medusa stuff
src/WizBot/data/medusae/
# other
output/
src/NadekoBot/output
src/NadekoBot/creds.yml
src/NadekoBot/Command Errors*.txt
src/NadekoBot/creds.yml
# credentials file before and after v3
src/NadekoBot/credentials.json
src/NadekoBot/old_credentials.json
src/NadekoBot/credentials.json.bak
src/NadekoBot/data/NadekoBot.db
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
@ -362,4 +362,15 @@ __pycache__/
### VisualStudio Patch ###
build/
site/
site/
## AI
.aider.*
PROMPT.md
.*rules
## Python pip/env files
Pipfile
Pipfile.lock
.venv

View File

@ -1,125 +0,0 @@
image: mcr.microsoft.com/dotnet/sdk:6.0
stages:
- build
- test
- upload-builds
- release
- publish-windows
- upload-windows-updater-release
variables:
project: "NadekoBot"
tests: "NadekoBot.Tests"
LINUX_X64_OUTPUT_DIR: "nadekobot-linux-x64"
LINUX_X64_RELEASE: "$CI_COMMIT_TAG-linux-x64-build.tar"
WIN_X64_OUTPUT_DIR: "nadekobot-windows-x64"
WIN_X64_RELEASE: "$CI_COMMIT_TAG-windows-x64-build.zip"
PACKAGE_REGISTRY_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/NadekoBot-build/${CI_COMMIT_TAG}"
INSTALLER_OUTPUT_DIR: "nadeko-installers/${CI_COMMIT_TAG}"
INSTALLER_FILE_NAME: "nadeko-setup-${CI_COMMIT_TAG}.exe"
build:
stage: build
script:
- "dotnet publish -c Release -r linux-x64 -o $LINUX_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
- "dotnet publish -c Release -r win7-x64 -o $WIN_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
artifacts:
paths:
- "$LINUX_X64_OUTPUT_DIR/"
- "$WIN_X64_OUTPUT_DIR/"
upload-builds:
stage: upload-builds
image: alpine:latest
rules:
- if: $CI_COMMIT_TAG
script:
- apk add --no-cache curl tar zip
- "tar cvf $LINUX_X64_RELEASE $LINUX_X64_OUTPUT_DIR/*"
- "zip -r $WIN_X64_RELEASE $WIN_X64_OUTPUT_DIR/*"
- |
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $LINUX_X64_RELEASE $PACKAGE_REGISTRY_URL/$LINUX_X64_RELEASE
- |
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $WIN_X64_RELEASE $PACKAGE_REGISTRY_URL/$WIN_X64_RELEASE
release:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
rules:
- if: $CI_COMMIT_TAG
script:
- |
release-cli create --name "NadekoBot v$CI_COMMIT_TAG" --description "## [Changelog](https://gitlab.com/Kwoth/nadekobot/-/blob/v4/CHANGELOG.md#$(echo "$CI_COMMIT_TAG" | sed "s/\.//g")-$(date +%d%m%Y))" --tag-name $CI_COMMIT_TAG \
--assets-link "{\"name\":\"${LINUX_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${LINUX_X64_RELEASE}\"}" \
--assets-link "{\"name\":\"${WIN_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${WIN_X64_RELEASE}\"}"
test:
stage: test
variables:
tests_path: "src/$tests"
script:
- "cd $tests_path"
- "dotnet test"
publish-windows:
stage: publish-windows
rules:
- if: '$CI_COMMIT_TAG'
image: scottyhardy/docker-wine
before_script:
- choco install dotnet-6.0-runtime -y
- choco install dotnet-6.0-sdk -y
- choco install innosetup -y
artifacts:
paths:
- "$INSTALLER_OUTPUT_DIR/$INSTALLER_FILE_NAME"
script:
- dotnet clean
- dotnet restore
- dotnet publish -c Release --runtime win7-x64 /p:Version=$CI_COMMIT_TAG src/NadekoBot
- $env:NADEKOBOT_INSTALL_VERSION = $CI_COMMIT_TAG
- iscc.exe "/O+" ".\exe_builder.iss"
tags:
- windows
upload-windows-updater-release:
stage: upload-windows-updater-release
rules:
- if: '$CI_COMMIT_TAG'
image:
name: amazon/aws-cli
entrypoint: [""]
script:
- sed -i "s/_INSTALLER_FILE_NAME_/$INSTALLER_FILE_NAME/g" releases-v3.json
- sed -i "s/_VERSION_/$CI_COMMIT_TAG/g" releases-v3.json
- aws --version
- aws --endpoint-url $AWS_SERVICE_URL s3api put-object --bucket "$AWS_BUCKET_NAME" --key "dl/bot/$INSTALLER_FILE_NAME" --acl public-read --body "$INSTALLER_OUTPUT_DIR/$INSTALLER_FILE_NAME"
- aws --endpoint-url $AWS_SERVICE_URL s3api put-object --bucket "$AWS_BUCKET_NAME" --key "dl/bot/releases-v3.json" --acl public-read --body "releases-v3.json"
# docker-build:
# # Use the official docker image.
# image: docker:latest
# stage: build
# services:
# - docker:dind
# before_script:
# - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
# # Default branch leaves tag empty (= latest tag)
# # All other branches are tagged with the escaped branch name (commit ref slug)
# script:
# - |
# if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
# tag=""
# echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = 'latest'"
# else
# tag=":$CI_COMMIT_REF_SLUG"
# echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
# fi
# - docker build --pull -t "$CI_REGISTRY_IMAGE${tag}" .
# - docker push "$CI_REGISTRY_IMAGE${tag}"
# # Run this job in a branch where a Dockerfile exists
# rules:
# - if: $CI_COMMIT_BRANCH
# exists:
# - Dockerfile

View File

@ -1,26 +0,0 @@
### Description
Write here a summary of the issue you're having.
### Version
- Write here whether you're using public Nadeko or hosting one yourself.
- If you are hosting, write down:
- The bot version (run the command .stats on Discord).
- Your operating system and its version.
- If you are on Windows, tell us whether you're using the updater version or the source version.
- If you are on Linux or OSX, tell us if you're hosting with tmux or pm2 or any other solution for managing processes.
### Reproduction Steps
- Describe, in detail, the steps necessary to consistently reproduce the issue.
- Preferably write the entire procedure in step-by-step instructions.
### Expected Behavior
Write here the behavior you were expecting to get from the bot.
### Actual Behavior
Write here the behavior you actually got from the bot.
### Screenshots
Include here any relevant screenshot that illustrates the issue you're having or that might help pinpoint the cause of the bug.
### Notes
Write here anything else you want to say that wasn't covered on the previous topics.

View File

@ -1,2 +0,0 @@
GitLab is for bug reports only.
Please, head over to https://nadeko.bot/suggest to make feature requests.

View File

@ -1,2 +0,0 @@
GitLab is for bug reports only.
Please, head over to our support server at https://invite.nadeko.bot/ and ask your question in the #help channel.

View File

@ -1,19 +0,0 @@
### Description
Write here a summary of the change(s) you're proposing and why this merge request would be a necessary or a nice addition to the project.
### Changes Proposed
Describe, item by item, all changes you'd like to propose. Write them in a list, one proposition per line. For example:
- Adds `DoStuff()` method to service X.
- Changes `SomeMethod()` on service Y, so it can handle situation Z better.
- Added a try/catch *somewhere*, so an exception is not thrown on the console when *something* happens.
- Replaced `AMethod()` by `AnotherMethod()` in *some command* for performance reasons.
### Details
Elaborate on the major and minor changes you've made to the source code. Try to explain why you've done something in a certain way.
### Screenshots
If applicable, send us screenshots of the result of your changes.
### Notes
Write here additional considerations that weren't covered on the previous topics.

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +1,49 @@
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /source
COPY src/NadekoBot/*.csproj src/NadekoBot/
COPY src/NadekoBot.Coordinator/*.csproj src/NadekoBot.Coordinator/
COPY src/NadekoBot.Generators/*.csproj src/NadekoBot.Generators/
COPY src/ayu/Ayu.Discord.Voice/*.csproj src/ayu/Ayu.Discord.Voice/
RUN dotnet restore src/NadekoBot/
# 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/NadekoBot
RUN set -xe; \
dotnet --version; \
dotnet publish -c Release -o /app --no-restore; \
mv /app/data /app/data_init; \
rm -Rf libopus* libsodium* opus.* runtimes/win* runtimes/osx* runtimes/linux-arm* runtimes/linux-mips*; \
find /app -type f -exec chmod -x {} \; ;\
chmod +x /app/NadekoBot
# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
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
RUN set -xe; \
useradd -m nadeko; \
apt-get update; \
apt-get install -y libopus0 libsodium23 libsqlite3-0 curl ffmpeg python3 python3-pip sudo; \
update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1; \
echo 'Defaults>nadeko env_keep+="ASPNETCORE_* DOTNET_* NadekoBot_* shard_id total_shards TZ"' > /etc/sudoers.d/nadeko; \
pip3 install --upgrade youtube-dl; \
apt-get remove -y python3-pip; \
chmod +x /usr/local/bin/youtube-dl
# 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
COPY docker-entrypoint.sh /usr/local/sbin/
ENV shard_id=0
ENV total_shards=1
RUN rm /app/data_init/lib/libsodium.so \
&& ln -s /usr/lib/libsodium.so.26 /app/data_init/lib/libsodium.so
VOLUME [ "/app/data" ]
VOLUME [ "app/data" ]
ENTRYPOINT [ "/usr/local/sbin/docker-entrypoint.sh" ]
CMD dotnet NadekoBot.dll "$shard_id" "$total_shards"
CMD [ "./WizBot" ]

619
LICENSE.AGPLv3 Normal file
View File

@ -0,0 +1,619 @@
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,7 +1,16 @@
Copyright 2021 Kwoth
Copyright (C) 2025 NadekoBot
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- 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
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
If you're looking for a commercial license, please reach out to me.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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

View File

@ -1,14 +1,50 @@
[![Discord](https://discordapp.com/api/guilds/117523346618318850/widget.png)](https://discord.gg/nadekobot)
[![Documentation Status](https://readthedocs.org/projects/nadekobot/badge/?version=latest)](http://nadekobot.readthedocs.io/en/v4/?badge=v4)
[![Discord Bots](https://discordbots.org/api/widget/status/116275390695079945.svg)](https://top.gg/bot/116275390695079945)
# WizBot
[![nadeko0](https://cdn.nadeko.bot/tutorial/docs-top.png)](https://nadeko.bot/)
[![nadeko1](https://cdn.nadeko.bot/tutorial/docs-mid.png)](https://invite.nadeko.bot/)
[![nadeko2](https://cdn.nadeko.bot/tutorial/docs-bot.png)](https://nadeko.bot/commands)
[![CI/CD](https://github.com/Wizkiller96/WizBot/actions/workflows/ci.yml/badge.svg)](https://github.com/Wizkiller96/WizBot/actions/workflows/ci.yml)
### Useful links
- [Self hosting Guides and Docs](https://nadekobot.readthedocs.io/en/v4)
- [Discord support server](https://discord.nadeko.bot)
WizBot is an open source Discord bot. It is written in C# and is built on .NET 8.
If you want to run your own instance of WizBot, please check out the [Self hosting Guides and Docs](https://docs.wizbot.cc).
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.

View File

@ -10,22 +10,24 @@ ProjectSection(SolutionItems) = preProject
CHANGELOG.md = CHANGELOG.md
LICENSE.md = LICENSE.md
README.md = README.md
.gitlab-ci.yml = .gitlab-ci.yml
Dockerfile = Dockerfile
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NadekoBot", "src\NadekoBot\NadekoBot.csproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WizBot", "src\WizBot\WizBot.csproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ayu", "ayu", "{6058FEDF-A318-4CD4-8F04-A7E8E7EC8874}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.Voice", "src\WizBot.Voice\WizBot.Voice.csproj", "{2F4CF6D6-0C2F-4944-B204-9508CDA53195}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ayu.Discord.Voice", "src\ayu\Ayu.Discord.Voice\Ayu.Discord.Voice.csproj", "{2F4CF6D6-0C2F-4944-B204-9508CDA53195}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.Tests", "src\WizBot.Tests\WizBot.Tests.csproj", "{DB448DD4-C97F-40E9-8BD3-F605FF1FF833}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NadekoBot.Tests", "src\NadekoBot.Tests\NadekoBot.Tests.csproj", "{DB448DD4-C97F-40E9-8BD3-F605FF1FF833}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.Coordinator", "src\WizBot.Coordinator\WizBot.Coordinator.csproj", "{AE9B7F8C-81D7-4401-83A3-643B38258374}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NadekoBot.Coordinator", "src\NadekoBot.Coordinator\NadekoBot.Coordinator.csproj", "{AE9B7F8C-81D7-4401-83A3-643B38258374}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.VotesApi", "src\WizBot.VotesApi\WizBot.VotesApi.csproj", "{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NadekoBot.Generators", "src\NadekoBot.Generators\NadekoBot.Generators.csproj", "{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wiz.Medusa", "src\Wiz.Medusa\Wiz.Medusa.csproj", "{E685977E-31A4-46F4-A5D7-4E3E39E82E43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NadekoBot.VotesApi", "src\NadekoBot.VotesApi\NadekoBot.VotesApi.csproj", "{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.Generators", "src\WizBot.Generators\WizBot.Generators.csproj", "{92770AF3-83EE-49F1-A0BB-79124D19A13D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WizBot.GrpcApiBase", "src\WizBot.GrpcApiBase\WizBot.GrpcApiBase.csproj", "{FB74B9EA-10B9-4542-ACB1-35523A95A587}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -58,30 +60,43 @@ Global
{AE9B7F8C-81D7-4401-83A3-643B38258374}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{AE9B7F8C-81D7-4401-83A3-643B38258374}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE9B7F8C-81D7-4401-83A3-643B38258374}.Release|Any CPU.Build.0 = Release|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8}.Release|Any CPU.Build.0 = Release|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F}.Release|Any CPU.Build.0 = Release|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E685977E-31A4-46F4-A5D7-4E3E39E82E43}.Release|Any CPU.Build.0 = Release|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92770AF3-83EE-49F1-A0BB-79124D19A13D}.Release|Any CPU.Build.0 = Release|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FB74B9EA-10B9-4542-ACB1-35523A95A587}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{45EC1473-C678-4857-A544-07DFE0D0B478} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{6058FEDF-A318-4CD4-8F04-A7E8E7EC8874} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{2F4CF6D6-0C2F-4944-B204-9508CDA53195} = {6058FEDF-A318-4CD4-8F04-A7E8E7EC8874}
{DB448DD4-C97F-40E9-8BD3-F605FF1FF833} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{AE9B7F8C-81D7-4401-83A3-643B38258374} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{3BC3BDF8-1A0B-45EB-AB2B-C0891D4D37B8} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{3BC82CFE-BEE7-451F-986B-17EDD1570C4F} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{E685977E-31A4-46F4-A5D7-4E3E39E82E43} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{92770AF3-83EE-49F1-A0BB-79124D19A13D} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{2F4CF6D6-0C2F-4944-B204-9508CDA53195} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
{FB74B9EA-10B9-4542-ACB1-35523A95A587} = {04929013-5BAB-42B0-B9B2-8F2BB8F16AF2}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5F3F555C-855F-4BE8-B526-D062D3E8ACA4}

View File

@ -1,20 +1,21 @@
#!/bin/sh
set -e;
data_init=/app/data_init
data=/app/data
set -e
# populate /app/data if empty
for i in $(ls $data_init)
do
if [ ! -e "$data/$i" ]; then
[ -f "$data_init/$i" ] && cp "$data_init/$i" "$data/$i"
[ -d "$data_init/$i" ] && cp -r "$data_init/$i" "$data/$i"
fi
done
data_init="/app/data_init"
data="/app/data"
# fix folder permissions
chown -R nadeko:nadeko "$data"
ls $data
# Merge data_init into data without overwrites.
# TODO: Barkranger will hopefull fix this, move for testing
cp -R -n $data_init/* $data
cp -n "$data_init/creds_example.yml" "$data/creds.yml"
# drop to regular user and launch command
exec sudo -u nadeko "$@"
ls $data
echo "Yt-dlp update"
# TODO: Update yt-dlp. It should not crash the entrypoint if ca-certificates is not installed
# yt-dlp -U
echo "Running WizBot"
exec "$@"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

View File

@ -1,25 +0,0 @@
# Readme for Commands List
## Bot Owner Only
- *Bot Owner Only* commands refer to the commands only the **owner** of the bot can use.
- *Bot Owner Only* commands do **not** refer to the owner of the **server**, just the owner of the **bot**.
- *Owner of the bot* is a person who is **hosting** their own bot, and their **ID** is inside of **creds.yml** file.
- You are **not** the bot **owner** if you invited the bot using **Carbonitex** or other invitation links.
## Music on the public Nadeko
- In case you got Nadeko in your server by the invitation from **Carbonitex**, our **GitLab** invite or **help (.h)**, music is disabled.
- Music is **disabled** due to large maintenance expenses
- If you want to have music module on your server, you will have to **host** the bot on your PC, or any of the external servers.
- How to **host** the bot, check the **guides** on the left side.
## NadekoFlowers
- NadekoFlowers is the **currency** of the public Nadeko.
- NadekoFlowers can be `.pick`ed after Nadeko plants a flower randomly after `.gc` has been enabled on a channel
- You can give NadekoFlowers to other users, using the command `.give X @person`.
- You can only give flowers you **own**.
- If you want to have **unlimited** number of flowers, you will have to **host** the bot.
- Commands `.award X @person` and `.take X @person` can only be used by the *bot owner*.
- If you `.plant` the flower, flower will be avaliable for everyone to `.pick` it. In that case you will **lose** the flower.

View File

@ -1,66 +0,0 @@
# Config
`.config` is the new `.bce`, it gives you a fast and easy way to edit most bot settings/values. Use `.h .config` for explanation.
Use `.config` to see the list of editable config files
Use `.config <config-name>` to see the list of settable properties on that config
Use `.config <config-name> <setting>` to see the current value and description
Use `.config <config-name> <setting> value` to set a new value
All settings are only available if you edit `data/[config-name].yml` files manually.
If you edit the files manually, you can reload configuration with `.configreload <config-name>`
The list below is not complete. Use commands above to see up-to-date list for your version.
## XP
`txt.cooldown` - Sets a timeout value in which a user cannot gain any more xp from sent messages. ( Value is in minutes )
`txt.per_msg` - Sets a value for the amount of xp a user will receive from sending a message.
`voice.per_minute` - Sets how much xp a user will receive from being active in a voice channel.
`voice.max_minutes` - Restricts a users xp gain to a certain amount of time spent in a voice channel.
*more settings may be available in `data/xp.yml` file*
## Games
`trivia.min_win_req` - Restricts a user's ability to make a trivia game with a win requirement less than the set value.
`trivia.currency_reward` - Sets the amount of currency a user will win if they place first in a completed trivia game.
*more settings may be available in `data/games.yml` file*
## Bot
`color.ok` - Sets a hex color that will be shown on the side bar of a successful command.
`color.error` - Sets a hex color that will be shown on the side bar of an unsuccessful command.
`color.pending` - Sets a hex color that will be shown on the side bar of a command that is currently in progress.
`help.text` - The text a user is DM'd when they invoke the `.h` command.
`help.dmtext` - The text a user will receive when they DM the bot directly.
`console.type` - Sets the style in which commands will show up in your console, values: `Simple`, `Normal`, `None`.
`locale` - Sets your native bot language, run the `.langli` command in a Discord channel for a full list of language options.
`prefix` - Sets default prefix for your bot.
*more settings may be available in `data/bot.yml` file*
## Gambling
`currency.name` - Sets the name for your bot's currency.
`currency.sign` - Sets the icon for your currency.
`minbet` - Minimum amount users can bet
`maxbet` - Maximum amount users can bet. Set 0 for unlimited
`gen.min` - Sets the minimum amount that can be spawned with `.gc` active.
`gen.max` - Sets the maximum amount that can be spawned with `.gc` active.
`gen.cd` - Sets a cooldown on how often a flower can spawn with `.gc` active ( Value is in seconds ).
`gen.chance` - Sets the likelihood that flowers will spawn with `.gc`. Value: ( 0.02 = 2% | 1 + 100% ).
`gen.has_pw` - Toggles wether the generated flowers will have a password at the top left of the image. Value: `true` or `false`
`bf.multi` - Sets the amount fo currency a user will win off of a winning a bet flip.
`waifu.min_price` - Sets the minimum price a user must pay to claim a user as their waifu.
`waifu.multi.reset` - Sets a multiplier for the `.waifureset` command.
`waifu.multi.crush_claim` - Sets a discount for a user that is claiming another user that has their affinity set to them.
`waifu.multi.normal_claim` - Amount a user would have to spend to claim a waifu with no affinity set.
`waifu.multi.divorce_value` - Sets how much a user would get if they divorce a waifu.
`waifu.multi.all_gifts` - Sets how much of a gifts value will be added to the value of the gifted waifu.
`waifu.multi.gift_effect` - Sets a bonus amount that a waifu will receive if they have their affinity set to the gifter.
`decay.percent` - Sets the percentage to decay all users currency daily.
`decay.maxdecay` - Sets the maximum a amount that a user's currency can decay in a day.
`decay.threshold` - Sets the minimum amount that a user must have to be eligible to receive a decay.
*more settings may be available in `data/gambling.yml` file*

View File

@ -1,7 +0,0 @@
# How to contribute
1. Make Merge Requests to the [**v4 branch**](https://gitlab.com/Kwoth/nadekobot/tree/v4)
2. Keep a single Merge Request to a single feature
3. Fill out the MR template
Thanks for all your help ^\_^

View File

@ -1,64 +0,0 @@
## Creds Guide
This document aims to guide you through the process of creating a Discord account for your bot
(the Discord Bot application), and inviting that account into your Discord server.
![Create a bot application and copy token to creds.yml file](https://cdn.nadeko.bot/tutorial/bot-creds-guide.gif)
- Go to [the Discord developer application page][DiscordApp].
- Log in with your Discord account.
- Click **New Application**.
- Fill out the `Name` field however you like.
- Go to the **Bot** tab on the left sidebar.
- Click on the `Add a Bot` button and confirm that you do want to add a bot to this app.
- **Optional:** Add bot's avatar and description.
- Copy your Token to `creds.yml` as shown above.
- Scroll down to the **`Privileged Gateway Intents`** section
- **Enable the following:**
- **PRESENCE INTENT**
- **SERVER MEMBERS INTENT**
- **MESSAGE CONTENT INTENT**
These are required for a number of features to function properly, and all should be on.
##### Getting Owner ID*(s)*:
- Go to your Discord server and attempt to mention yourself, but put a backslash at the start
*(to make it slightly easier, add the backslash after the mention has been typed)*.
- For example, the message `\@fearnlj01#3535` will appear as `<@145521851676884992>` after you send the message.
- The message will appear as a mention if done correctly. Copy the numbers from it **`145521851676884992`** and replace the big number on the `OwnerIds` section with your user ID.
- Save the `creds.yml` file.
- If done correctly, you should now be the bot owner. You can add multiple owners by adding them below the first one. Indentation matters.
For a single owner, it should look like this:
```yml
OwnerIds:
- 105635576866156544
```
For multiple owners, it should look like this:
```yml
OwnerIds:
- 105635123466156544
- 145521851676884992
- 341420590009417729
```
#### Inviting your bot to your server
![Invite the bot to your server](https://cdn.nadeko.bot/tutorial/bot-invite-guide.gif)
- On the **General Information** tab, copy your `Application ID` from your [applications page][DiscordApp].
- Replace the `YOUR_CLIENT_ID_HERE` in this link:
`https://discordapp.com/oauth2/authorize?client_id=YOUR_CLIENT_ID_HERE&scope=bot&permissions=66186303` with your `Client ID`
- The link should now look something like this:
`https://discordapp.com/oauth2/authorize?client_id=123123123123&scope=bot&permissions=66186303`
- Access that newly created link, pick your Discord server, click `Authorize` and confirm with the captcha at the end
- The bot should now be in your server
That's it! You may now go back to the installation guide you were following before 🎉
[DiscordApp]: https://discordapp.com/developers/applications/me

View File

@ -1,44 +0,0 @@
## Custom Reactions / Expressions
### Important
- For modifying **global** custom reactions, the ones which will work across all the servers your bot is connected to, you **must** be a Bot Owner.
You must also use the commands for adding, deleting and listing these reactions in a direct message with the bot.
- For modifying **local** custom reactions, the ones which will only work on the server that they are added on, it is required to have the **Administrator** permission.
You must also use the commands for adding, deleting and listing these reactions in the server you want the custom reactions to work on.
### Commands and Their Use
| Command Name | Description | Example |
| :----------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------- |
| `.acr` | Add a custom reaction with a trigger and a response. Running this command in a server requries the Administrator permission. Running this command in DM is Bot Owner only, and adds a new global custom reaction. | `.acr "hello" Hi there, %user%!` |
| `.lcr` | Lists a page of global or server custom reactions (15 reactions per page). Running this command in a DM will list the global custom reactions, while running it in a server will list that server's custom reactions. | `.lcr 1` |
| `.dcr` | Deletes a custom reaction based on the provided index. Running this command in a server requires the Administrator permission. Running this command in DM is Bot Owner only, and will delete a global custom reaction. | `.dcr 5` |
#### Now that we know the commands let's take a look at an example of adding a command with `.acr`,
`.acr "Nice Weather" It sure is, %user%!`
This command can be split into two different arguments:
- The trigger, `"Nice Weather"`
- And the response, `It sure is, %user%!`
An important thing to note about the triger is that, to be more than one word, we had to wrap it with quotation marks, `"Like this"` otherwise, only the first word would have been recognised as the trigger, and the second word would have been recognised as part of the response.
There's no special requirement for the formatting of the response, so we could just write it in exactly the same way we want it to respond, albeit with a placeholder - which will be explained in this next section.
Now, if that command was ran in a server, anyone on that server can make the bot mention them, saying `It sure is, @Username` anytime they say "Nice Weather". If the command is ran in a direct message with the bot, then the custom reaction can be used on every server the bot is connected to.
### Block global Custom Reactions
If you want to disable a global custom reaction which you do not like, and you do not want to remove it, or you are not the bot owner, you can do so by adding a new Custom Reaction with the same trigger on your server, and set the response to `-`.
For example:
`.acr /o/ -`
Now if you try to trigger `/o/`, it won't print anything even if there is a global custom reaction with the same name.
### Placeholders!
To learn about placeholders, go [here](placeholders.md)

View File

@ -1,33 +0,0 @@
# Setting up NadekoBot with Docker
# DO NOT USE YET - WORK IN PROGRESS
### Docker Compose
```yml
version: "3.7"
services:
nadeko:
image: registry.gitlab.com/veovis/nadekobot:v3-docker
depends_on:
- redis
environment:
TZ: Europe/Paris
#NadekoBot_RedisOptions: redis,name=nadeko
#NadekoBot_ShardRunCommand: dotnet
#NadekoBot_ShardRunArguments: /app/NadekoBot.dll {0} {1}
volumes:
- /srv/nadeko/conf/creds.yml:/app/creds.yml:ro
- /srv/nadeko/data:/app/data
redis:
image: redis:4-alpine
sysctls:
- net.core.somaxconn=511
command: redis-server --maxmemory 32M --maxmemory-policy volatile-lru
volumes:
- /srv/nadeko/redis-data:/data
```
### Updating
- `cd /srv/nadeko`
- `docker-compose pull`
- `docker-compose up -d`

View File

@ -1,319 +0,0 @@
# Setting up NadekoBot on Linux
| Table of Contents |
| :-------------------------------------------------- |
| [Linux From Source] |
| [Source Update Instructions] |
| [Linux Release] |
| [Release Update Instructions] |
| [Tmux (Preferred Method)] |
| [Systemd] |
| [Systemd + Script] |
| [Setting up Nadeko on a VPS (Digital Ocean)] |
#### Operating System Compatibility
It is recommended that you use **Ubuntu 20.04**, as there have been nearly no problems with it. Also, **32-bit systems are incompatible**.
##### Compatible operating systems:
- Ubuntu: 16.04, 18.04, 20.04, 21.04, 21.10
- Mint: 19, 20
- Debian: 9, 10
- CentOS: 7
- openSUSE
- Fedora: 33, 34, 35
## Linux From Source
##### Migration from v3 -> v4
Follow the following few steps only if you're migrating from v3. If not, skip to installation instructions.
Use the new installer script: `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
> - Install prerequisites (type `1` and press `enter`)
> - Download (type `2` and press `enter`)
> - Run (type `3` and press `enter`)
> - Done
##### Installation Instructions
Open Terminal (if you're on an installation with a window manager) and navigate to the location where you want to install the bot (for example `cd ~`)
1. Download and run the **new** installer script `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
2. Install prerequisites (type `1` and press enter)
3. Download the bot (type `2` and press enter)
4. Exit the installer (type `6` and press enter)
5. Copy the creds.yml template `cp nadekobot/output/creds_example.yml nadekobot/output/creds.yml`
6. Open `nadekobot/output/creds.yml` with your favorite text editor. We will use nano here
- `nano nadekobot/output/creds.yml`
7. [Click here to follow creds guide](../../creds-guide)
- After you're done, you can close nano (and save the file) by inputting, in order
- `CTRL` + `X`
- `Y`
- `Enter`
8. Run the installer script again `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
9. Run the bot (type `3` and press enter)
##### Source Update Instructions
1. ⚠ Stop the bot ⚠
2. Update and run the **new** installer script `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
3. Update the bot (type `2` and press enter)
4. Run the bot (type `3` and press enter)
5. 🎉
## Linux Release
**⚠ IF YOU ARE FOLLOWING THE GUIDE ABOVE, IGNORE THIS SECTION ⚠**
##### Installation Instructions
1. Download the latest release from <https://gitlab.com/Kwoth/nadekobot/-/releases>
- Look for the file called "X.XX.X-linux-x64-build.tar" (where X.XX.X is a series of numbers) and download it
2. Untar it
- ⚠ Make sure that you change X.XX.X to the same series of numbers as in step 1!
- `tar xf X.XX.X-linux-x64-build.tar`
3. Rename the `nadekobot-linux-x64` to `nadekobot`
- `mv nadekobot-linux-x64 nadekobot`
4. Move into nadekobot directory and make NadekoBot executable
- `cd nadekobot && chmod +x NadekoBot`
5. Copy the creds.yml template
- `cp creds_example.yml creds.yml`
6. Open `creds.yml` with your favorite text editor. We will use nano here
- `nano nadekobot/output/creds.yml`
8. [Click here to follow creds guide](../../creds-guide)
- After you're done, you can close nano (and save the file) by inputting, in order
- `CTRL` + `X`
- `Y`
- `Enter`
9. Run the bot
- `./NadekoBot`
##### Release Update Instructions
1. Stop the bot
2. Download the latest release from <https://gitlab.com/Kwoth/nadekobot/-/releases>
- Look for the file called "x.x.x-linux-x64-build.tar" (where `X.X.X` is a version, for example 3.0.4) and download it
3. Untar it
- ⚠ Make sure that you change `X.X.X` to the same series of numbers as in step 2!
- `tar xf x.x.x-linux-x64-build.tar`
4. Rename the old nadekobot directory to nadekobot-old (remove your old backup first if you have one, or back it up under a different name)
- `rm -rf nadekobot-old 2>/dev/null`
- `mv nadekobot nadekobot-old`
5. Rename the new nadekobot directory to nadekobot
- `mv nadekobot-linux-x64 nadekobot`
6. Remove old strings and aliases to avoid overwriting the updated versions of those files
- ⚠ If you've modified said files, back them up instead
- `rm nadekobot-old/data/aliases.yml`
- `rm -r nadekobot-old/data/strings`
7. Copy old data
- `cp -RT nadekobot-old/data/ nadekobot/data`
8. Copy creds.yml
- `cp nadekobot-old/creds.yml nadekobot/`
9. Move into nadekobot directory and make the NadekoBot executable
- `cd nadekobot && chmod +x NadekoBot`
10. Run the bot
- `./NadekoBot`
🎉 Enjoy
##### Steps 3 - 9 as a single command
Don't forget to change X.XX.X to match step 2.
```sh
tar xf X.XX.X-linux-x64-build.tar && \
rm -rf nadekobot-old 2>/dev/null && \
mv nadekobot nadekobot-old && \
mv nadekobot-linux-x64 nadekobot && \
rm nadekobot-old/data/aliases.yml && \
rm -r nadekobot-old/data/strings && \
cp -RT nadekobot-old/data/ nadekobot/data && \
cp nadekobot-old/creds.yml nadekobot/ && \
cd nadekobot && chmod +x NadekoBot
```
## Running Nadeko
While there are two run modes built into the installer, these options only run Nadeko within the current session. Below are 3 methods of running Nadeko as a background process.
### Tmux Method (Preferred)
Using `tmux` is the simplest method, and is therefore recommended for most users.
1. Start a tmux session:
- `tmux`
2. Navigate to the project's root directory
- Project root directory location example: `/home/user/nadekobot/`
3. Enter the `output` directory:
- `cd output`
4. Run the bot using:
- `dotnet NadekoBot.dll`
5. Detatch the tmux session:
- Press `Ctrl` + `B`
- Then press `D`
Nadeko should now be running in the background of your system. To re-open the tmux session to either update, restart, or whatever, execute `tmux a`.
### Systemd
Compared to using tmux, this method requires a little bit more work to set up, but has the benefit of allowing Nadeko to automatically start back up after a system reboot or the execution of the `.die` command.
1. Navigate to the project's root directory
- Project root directory location example: `/home/user/nadekobot/`
2. Use the following command to create a service that will be used to start Nadeko:
```bash
echo "[Unit]
Description=NadekoBot service
After=network.target
StartLimitIntervalSec=60
StartLimitBurst=2
[Service]
Type=simple
User=$USER
WorkingDirectory=$PWD/output
# If you want Nadeko to be compiled prior to every startup, uncomment the lines
# below. Note that it's not neccessary unless you are personally modifying the
# source code.
#ExecStartPre=/usr/bin/dotnet build ../src/NadekoBot/NadekoBot.csproj -c Release -o output/
ExecStart=/usr/bin/dotnet NadekoBot.dll
Restart=on-failure
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=NadekoBot
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/nadeko.service
```
3. Make the new service available:
- `sudo systemctl daemon-reload`
4. Start Nadeko:
- `sudo systemctl start nadeko.service && sudo systemctl enable nadeko.service`
### Systemd + Script
This method is similar to the one above, but requires one extra step, with the added benefit of better error logging and control over what happens before and after the startup of Nadeko.
1. Locate the project and move to its parent directory
- Project location example: `/home/user/nadekobot/`
- Parent directory example: `/home/user/`
2. Use the following command to create a service that will be used to execute `NadekoRun.sh`:
```bash
echo "[Unit]
Description=NadekoBot service
After=network.target
StartLimitIntervalSec=60
StartLimitBurst=2
[Service]
Type=simple
User=$USER
WorkingDirectory=$_WORKING_DIR
ExecStart=/bin/bash NadekoRun.sh
Restart=on-failure
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=NadekoBot
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/nadeko.service
```
3. Make the new service available:
- `sudo systemctl daemon-reload`
4. Use the following command to create a script that will be used to start Nadeko:
```bash
{
echo '#!/bin/bash'
echo ""
echo "echo \"Running NadekoBot in the background with auto restart\"
youtube-dl -U
# If you want Nadeko to be compiled prior to every startup, uncomment the lines
# below. Note that it's not necessary unless you are personally modifying the
# source code.
#echo \"Compiling NadekoBot...\"
#cd \"$PWD\"/nadekobot
#dotnet build src/NadekoBot/NadekoBot.csproj -c Release -o output/
echo \"Starting NadekoBot...\"
while true; do
if [[ -d $PWD/nadekobot/output ]]; then
cd $PWD/nadekobot/output || {
echo \"Failed to change working directory to $PWD/nadekobot/output\" >&2
echo \"Ensure that the working directory inside of '/etc/systemd/system/nadeko.service' is correct\"
echo \"Exiting...\"
exit 1
}
else
echo \"$PWD/nadekobot/output doesn't exist\"
exit 1
fi
dotnet NadekoBot.dll || {
echo \"An error occurred when trying to start NadekBot\"
echo \"Exiting...\"
exit 1
}
echo \"Waiting for 5 seconds...\"
sleep 5
youtube-dl -U
echo \"Restarting NadekoBot...\"
done
echo \"Stopping NadekoBot...\""
} > NadekoRun.sh
```
5. Start Nadeko:
- `sudo systemctl start nadeko.service && sudo systemctl enable nadeko.service`
### Setting up Nadeko on a Linux VPS (Digital Ocean Droplet)
If you want Nadeko to play music for you 24/7 without having to hosting it on your PC and want to keep it cheap, reliable and convenient as possible, you can try Nadeko on Linux Digital Ocean Droplet using the link [DigitalOcean](http://m.do.co/c/46b4d3d44795/) (by using this link, you will get **$10 credit** and also support Nadeko)
**Setting up NadekoBot**
Assuming you have followed the link above to setup an account and a Droplet with a 64-bit operational system on Digital Ocean and got the `IP address and root password (in your e-mail)` to login, it's time to get started.
**This section is only relevant to those who want to host Nadeko on DigitalOcean. Go through this whole section before setting the bot up.**
#### Prerequisites
- Download [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html)
- Download [WinSCP](https://winscp.net/eng/download.php) *(optional)*
- [Create and invite the bot](../../creds-guide).
#### Starting up
- **Open PuTTY** and paste or enter your `IP address` and then click **Open**.
If you entered your Droplets IP address correctly, it should show **login as:** in a newly opened window.
- Now for **login as:**, type `root` and press enter.
- It should then ask for a password. Type the `root password` you have received in your e-mail address, then press Enter.
If you are running your droplet for the first time, it will most likely ask you to change your root password. To do that, copy the **password you've received by e-mail** and paste it on PuTTY.
- To paste, just right-click the window (it won't show any changes on the screen), then press Enter.
- Type a **new password** somewhere, copy and paste it on PuTTY. Press Enter then paste it again.
**Save the new password somewhere safe.**
After that, your droplet should be ready for use. [Follow the guide from the beginning](#linux-from-source) to set Nadeko up on your newly created VPS.
[Linux From Source]: #linux-from-source
[Source Update Instructions]: #source-update-instructions
[Linux Release]: #linux-release
[Release Update Instructions]: #release-update-instructions
[Tmux (Preferred Method)]: #tmux-preferred-method
[Systemd]: #systemd
[Systemd + Script]: #systemd-script
[Setting up Nadeko on a VPS (Digital Ocean)]: #setting-up-nadeko-on-a-linux-vps-digital-ocean-droplet

View File

@ -1,125 +0,0 @@
## MacOS From Source
Open Terminal (if you don't know how to, click on the magnifying glass on the top right corner of your screen and type **Terminal** on the window that pops up) and navigate to the location where you want to install the bot (for example `cd ~`)
##### Installing Homebrew, wget and dotnet
###### Homebrew/wget
*Skip this step if you already have homebrew installed*
- Copy and paste this command, then press Enter:
- `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
- Install wget
- `brew install wget`
###### Dotnet
- Download [.net6 SDK](https://dotnet.microsoft.com/download/dotnet/6.0)
- Open the `.pkg` file you've downloaded and install it.
- Run this command in Terminal. There might be output. If there is, disregard it. (copy-paste the entire block)
```bash
sudo mkdir /usr/local/bin
sudo mkdir /usr/local/lib
```
- Run this command in Terminal. There won't be any output. (copy-paste the entire block):
```bash
sudo ln -s /usr/local/share/dotnet/dotnet /usr/local/bin
sudo ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/
sudo ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/
```
##### Installation Instructions
1. Download and run the **new** installer script `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
2. Install prerequisites (type `1` and press enter)
3. Download the bot (type `2` and press enter)
4. Exit the installer in order to set up your `creds.yml`
5. Copy the creds.yml template
`cp nadekobot/output/creds_example.yml nadekobot/output/creds.yml`
6. Open `nadekobot/output/creds.yml` with your favorite text editor. We will use nano here
- `nano nadekobot/output/creds.yml`
7. [Enter your bot's token](#creds-guide)
- After you're done, you can close nano (and save the file) by inputting, in order
- `CTRL`+`X`
- `Y`
- `Enter`
8. Run the bot (type `3` and press enter)
##### Update Instructions
1. ⚠ Stop the bot
2. Update and run the **new** installer script `cd ~ && wget -N https://gitlab.com/Kwoth/nadeko-bash-installer/-/raw/v4/linuxAIO.sh && bash linuxAIO.sh`
3. Update the bot (type `2` and press enter)
4. Run the bot (type `3` and press enter)
5. 🎉
## MacOS Manual Release installation instructions
⚠ IF YOU ARE FOLLOWING THE GUIDE ABOVE, IGNORE THIS SECTION ⚠
##### Installation Instructions
1. Download the latest release from <https://gitlab.com/Kwoth/nadekobot/-/releases>
- Look for the file called "X.XX.X-linux-x64-build.tar" (where X.XX.X is a series of numbers) and download it
2. Untar it
⚠ Make sure that you change X.XX.X to the same series of numbers as in step 1!
- `tar xf X.XX.X-linux-x64-build.tar`
3. Rename the `nadekobot-linux-x64` to `nadekobot`
- `mv nadekobot-linux-x64 nadekobot`
4. Move into nadekobot directory and make NadekoBot executable
- `cd nadekobot && chmod +x NadekoBot`
5. Copy the creds.yml template
- `cp creds_example.yml creds.yml`
6. Open `creds.yml` with your favorite text editor. We will use nano here
- `nano nadekobot/output/creds.yml`
8. [Enter your bot's token](#creds-guide)
- After you're done, you can close nano (and save the file) by inputting, in order
- `CTRL`+`X`
- `Y`
- `Enter`
9. Run the bot
- `./NadekoBot`
##### Update Instructions
1. Stop the bot
2. Download the latest release from <https://gitlab.com/Kwoth/nadekobot/-/releases>
- Look for the file called "X.XX.X-linux-x64-build.tar" (where X.XX.X is a series of numbers) and download it
3. Untar it
⚠ Make sure that you change X.XX.X to the same series of numbers as in step 2!
- `tar xf 2.99.8-linux-x64-build.tar`
4. Rename the old nadekobot directory to nadekobot-old (remove your old backup first if you have one, or back it up under a different name)
- `rm -rf nadekobot-old 2>/dev/null`
- `mv nadekobot nadekobot-old`
5. Rename the new nadekobot directory to nadekobot
- `mv nadekobot-linux-x64 nadekobot`
6. Remove old strings and aliases to avoid overwriting the updated versions of those files
⚠ If you've modified said files, back them up instead
- `rm nadekobot-old/data/aliases.yml`
- `rm -r nadekobot-old/data/strings`
7. Copy old data
- `cp -RT nadekobot-old/data/ nadekobot/data/`
8. Copy creds.yml
- `cp nadekobot-old/creds.yml nadekobot/`
9. Move into nadekobot directory and make the NadekoBot executable
- `cd nadekobot && chmod +x NadekoBot`
10. Run the bot
- `./NadekoBot`
🎉 Enjoy
##### Steps 3 - 9 as a single command
Don't forget to change X.XX.X to match step 2.
```sh
tar xf X.XX.X-linux-x64-build.tar && \
rm -rf nadekobot-old 2>/dev/null && \
mv nadekobot nadekobot-old && \
mv nadekobot-linux-x64 nadekobot && \
rm nadekobot-old/data/aliases.yml && \
rm -r nadekobot-old/data/strings && \
cp -RT nadekobot-old/data/ nadekobot/data/ && \
cp nadekobot-old/creds.yml nadekobot/ && \
cd nadekobot && chmod +x NadekoBot
```

View File

@ -1,133 +0,0 @@
## Setting Up NadekoBot on Windows With the Updater
| Table of Contents|
| :---------------------------------------------------------------------------------------------------------------------------|
| [Prerequisites](#prerequisites) |
| [Setup](#setup) |
| [Starting the Bot](#starting-the-bot) |
| [Updating Nadeko](#updating-nadeko) |
| [Manually Installing the Prerequisites from the Updater](#music-prerequisites) |
*Note: If you want to make changes to Nadeko's source code, please follow the [From Source](#windows-from-source) guide instead.*
*If you have Windows 7 or a 32-bit system, please refer to the [From Source](#windows-from-source)) guide.*
#### Prerequisites
- Windows 8 or later (64-bit)
- [Create a Discord Bot application and invite the bot to your server](../creds-guide.md)
**Optional**
- [Notepad++] (makes it easier to edit your credentials)
- [Visual C++ 2010 (x86)] and [Visual C++ 2017 (x64)] (both are required if you want Nadeko to play music - restart Windows after installation)
#### Setup
- Download and run the [NadekoBot v3 Updater][Updater].
- Click on the + at the top left to create a new bot.
![NadekoBot Updater](https://i.imgur.com/FmR7F7o.png "NadekoBot Updater")
- Give your bot a name and then click **`Go to setup`** at the lower right.
![Create a new bot](https://i.imgur.com/JxtRk9e.png "Create a new bot")
- Click on **`DOWNLOAD`** at the lower right
![Bot Setup](https://i.imgur.com/HqAl36p.png "Bot Setup")
- Click on **`Install`** next to **`Redis`**.
- Note: If Redis fails to install, install Redis manually here: [Redis Installer](https://github.com/MicrosoftArchive/redis/releases/tag/win-3.0.504) Download and run the **`.msi`** file.
- If you will use the music module, click on **`Install`** next to **`FFMPEG`** and **`Youtube-DL`**.
- If any dependencies fail to install, you can temporarily disable your Windows Defender/AV until you install them. If you don't want to, then read [the last section of this guide](#Manual-Prerequisite-Installation).
- When installation is finished, click on **`CREDS`** to the left of **`RUN`** at the lower right.
- Follow the guide on how to [Set up the creds.yml](../../creds-guide) file.
#### Starting the bot
- Either click on **`RUN`** button in the updater or run the bot via its desktop shortcut.
### If you get a "No owner channels created..." message. Please follow the creds guide again [**HERE**](../../creds-guide).
#### Updating Nadeko
- Make sure Nadeko is closed and not running
(Run `.die` in a connected server to ensure it's not running).
- Open NadekoBot Updater
- Click on your bot at the upper left (looks like a spy).
- Click on **`Check for updates`**.
- If updates are available, you will be able to click on the Update button.
- Launch the bot
- You've updated and are running again, easy as that!
#### Manual Prerequisite Installation
You can still install them manually:
- [Redis Installer](https://github.com/MicrosoftArchive/redis/releases/tag/win-3.0.504) - Download and run the **`.msi`** file
- [ffmpeg-32bit] | [ffmpeg-64bit] - Download the **appropriate version** for your system (32 bit if you're running a 32 bit OS, or 64 if you're running a 64bit OS). Unzip it, and move `ffmpeg.exe` to a path that's in your PATH environment variable. If you don't know what that is, then just move the `ffmpeg.exe` file to NadekoBot/system
- [youtube-dl] - Click to download the file. Then put `youtube-dl.exe` in a path that's in your PATH environment variable. If you don't know what that is, then just move the `youtube-dl.exe` file to NadekoBot/system
### Windows From Source
⚠ IF YOU ARE FOLLOWING THE GUIDE ABOVE, IGNORE THIS SECTION ⚠
##### Prerequisites
**Install these before proceeding or your bot will not work!**
- [.net 6](https://dotnet.microsoft.com/download/dotnet/6.0) - needed to compile and run the bot
- [git](https://git-scm.com/downloads) - needed to clone the repository (you can also download the zip manually and extract it, but this guide assumes you're using git)
- [redis](https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi) - to cache things needed by some features and persist through restarts
##### Installation Instructions
Open PowerShell (press windows button on your keyboard and type powershell, it should show up; alternatively, right click the start menu and select Windows PowerShell), and navigate to the location where you want to install the bot (for example `cd ~/Desktop/`)
1. `git clone https://gitlab.com/kwoth/nadekobot -b v4 --depth 1`
2. `cd nadekobot`
3. `dotnet publish -c Release -o output/ src/NadekoBot/`
4. `cd output`
5. `cp creds_example.yml creds.yml`
6. Open `creds.yml` with your favorite text editor (Please don't use Notepad or WordPad. You can use Notepad++, VSCode, Atom, Sublime, or something similar)
7. [Enter your bot's token](#creds-guide)
8. Run the bot `dotnet NadekoBot.dll`
9. 🎉
##### Update Instructions
Open PowerShell as described above and run the following commands:
1. Stop the bot
- ⚠️ Make sure you don't have your database, credentials or any other nadekobot folder open in some application, this might prevent some of the steps from executing succesfully
2. Navigate to your bot's folder, example:
- `cd ~/Desktop/nadekobot`
3. Pull the new version
- `git pull`
- ⚠️ If this fails, you may want to stash or remove your code changes if you don't know how to resolve merge conflicts
4. **Backup** old output in case your data is overwritten
- `cp -r -fo output/ output-old`
5. Build the bot again
- `dotnet publish -c Release -o output/ src/NadekoBot/`
6. Remove old strings and aliases to avoid overwriting the updated versions of those files
- ⚠ If you've modified said files, back them up instead
- `rm output-old/data/aliases.yml`
- `rm -r output-old/data/strings`
7. Copy old data
- `cp -Recurse .\output-old\data\ .\output\ -Force`
8. Copy creds.yml
- `cp output-old/creds.yml output/`
9. Run the bot
- `cd output`
- `dotnet NadekoBot.dll`
🎉 Enjoy
#### Music prerequisites
In order to use music commands, you need ffmpeg and youtube-dl installed.
- [ffmpeg-32bit] | [ffmpeg-64bit] - Download the **appropriate version** for your system (32 bit if you're running a 32 bit OS, or 64 if you're running a 64bit OS). Unzip it, and move `ffmpeg.exe` to a path that's in your PATH environment variable. If you don't know what that is, just move the `ffmpeg.exe` file to `NadekoBot/output`.
- [youtube-dl] - Click to download the file, then move `youtube-dl.exe` to a path that's in your PATH environment variable. If you don't know what that is, just move the `youtube-dl.exe` file to `NadekoBot/system`.
[Updater]: https://dl.nadeko.bot/
[Notepad++]: https://notepad-plus-plus.org/
[.net]: https://dotnet.microsoft.com/download/dotnet/5.0
[Redis]: https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi
[Visual C++ 2010 (x86)]: https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x86.exe
[Visual C++ 2017 (x64)]: https://aka.ms/vs/15/release/vc_redist.x64.exe
[ffmpeg-32bit]: https://cdn.nadeko.bot/dl/ffmpeg-32.zip
[ffmpeg-64bit]: https://cdn.nadeko.bot/dl/ffmpeg-64.zip
[youtube-dl]: https://yt-dl.org/downloads/latest/youtube-dl.exe

View File

@ -1,43 +0,0 @@
# NadekoBot Documentation
<!-- ![img][header] -->
## Inviting Nadeko
There are two versions of Nadeko, a public bot and a self-hostable bot.
To invite public Nadeko to your server or to view its commands, click on the buttons below:
[:material-plus: Add Nadeko to your server][invite]{ .md-button .md-button--primary }
[:material-format-list-text: View commands][commands]{ .md-button }
To self-host your own Nadeko, use the guides below:
- [:material-microsoft-windows: Windows guide][windows-guide]
- [:material-linux: Linux guide][linux-guide]
- [:material-apple: Mac OS guide][macos-guide]
Alternatively, you may also setup the bot [from source][from-source-guide] if you want to modify the code.
In case you need any help, join our [Discord server][discord-server] where we may provide support.
---
## About Nadeko
NadekoBot is an [open source project][gitlab]. Any issues with the bot may be filed [here][issues].
If you're unsure whether something is an issue, ask in our support server first.
[Donations are welcome][donate], and we rely on your contributions to help keep the project alive.
[invite]: https://invite.nadeko.bot/
[commands]: https://nadeko.bot/commands/
[windows-guide]: ./guides/windows-guide.md
[linux-guide]: ./guides/linux-guide.md
[macos-guide]: ./guides/osx-guide.md
[from-source-guide]: ./guides/from-source.md
[discord-server]: https://discord.nadeko.bot/
[gitlab]: https://gitlab.com/Kwoth/nadekobot
[issues]: https://gitlab.com/Kwoth/nadekobot/issues
[donate]: ./donate.md

View File

@ -1,225 +0,0 @@
## Setting up your API keys
This part is completely optional, **however it's necessary for music and a few other features to work properly**.
- **GoogleAPIKey**
- Required for Youtube Song Search, Playlist queuing, and a few more things.
- Follow these steps on how to setup Google API keys:
- Go to [Google Console][Google Console] and log in.
- Create a new project (name does not matter).
- Once the project is created, go into `Library`
- Under the `YouTube APIs` section
- Select `YouTube Data API v3`,
- Click enable.
- Search for `Custom Search API`
- Select `Custom Search API`,
- Click enable.
- Open up the `Navigation menu` on the top right with the three lines.
- select `APIs & Services`, then select `Credentials`,
- Click `Create Credentials` button,
- Click on `API Key`
- A new window will appear with your `Google API key`
*NOTE: You don't really need to click on `RESTRICT KEY`, just click on `CLOSE` when you are done.*
- Copy the key.
- Open up `creds.yml` and look for `GoogleAPIKey`, paste your API key after the `:`.
- It should look like this:
```yml
GoogleApiKey: AIzaSyDSci1sdlWQOWNVj1vlXxxxxxbk0oWMEzM
```
- **MashapeKey**
- Required for Hearthstone cards.
- Api key obtained on https://rapidapi.com (register -> go to MyApps -> Add New App -> Enter Name -> Application key)
- Copy the key and paste it into `creds.yml`
- **OsuApiKey**
- Required for Osu commands
- You can get this key [here](https://osu.ppy.sh/p/api).
- **CleverbotApiKey**
- Required if you want to use Cleverbot. It's currently a paid service.
- You can get this key [here](http://www.cleverbot.com/api/).
- **PatreonAccessToken**
- For Patreon creators only.
- **PatreonCampaignId**
- For Patreon creators only. Id of your campaign.
- **TwitchClientId**
- Mandatory for following twitch streams with `.twitch` (or `.stadd` with twitch link)
- Go to [apps page](https://dev.twitch.tv/console/apps/create) on twitch and register your application.
- You need 2FA enabled on twitch in order to create an application
- You can set `http://localhost` as the OAuth Redirect URL (and press Add button)
- Select `Chat Bot` from the Category dropdown
- Once created, clicking on your application will show a new Client ID field
- Copy it to your creds.yml as shown below
```yml
TwitchClientId: "516tr61tr1qweqwe86trg3g"
```
- **LocationIqApiKey**
- Optional. Used only for the `.time` command. https://locationiq.com api key (register and you will receive the token in the email).
- **TimezoneDbApiKey**
- Optional. Used only for the `.time` command. https://timezonedb.com api key (register and you will receive the token in the email **YOU HAVE TO ACTIVEATE IT AFTER YOU GET IT**).
- **CoinmarketcapApiKey**
- Optional. Used only for the `.crypto` command. You can use crypto command without it, but you might get ratelimited from time to time, as all self-hosters share the default api key. https://pro.coinmarketcap.com/
##### Additional Settings
- **TotalShards**
- Required if the bot will be connected to more than 2500 servers.
- Most likely unnecessary to change until your bot is added to more than 2500 servers.
- **RedisOptions**
- Required if the Redis instance is not on localhost or on non-default port.
- You can find all available options [here](https://stackexchange.github.io/StackExchange.Redis/Configuration.html).
- **RestartCommand**
- Required if you want to be able to use the `.restart` command
- If you're using the CLI installer or Linux/OSX, it's easier and more reliable setup Nadeko with auto-restart and just use `.die`
For Windows (Updater), add this to your `creds.yml`
```yml
RestartCommand:
Cmd: "NadekoBot.exe"
args: "{0}"
```
For Windows (Source), Linux or OSX, add this to your `creds.yml`
```yml
RestartCommand:
Cmd: dotnet
Args: "NadekoBot.dll -- {0}"
```
---
#### End Result
**This is an example of how the `creds.yml` looks like with multiple owners, the restart command (optional) and some of the API keys (also optional):**
```yml
# DO NOT CHANGE
version: 1
# Bot token. Do not share with anyone ever -> https://discordapp.com/developers/applications/
token: 'MTE5Nzc3MDIxMzE5NTc3NjEw.VlhNCw.BuqJFyzdIUAK1PRf1eK1Cu89Jew'
# List of Ids of the users who have bot owner permissions
# **DO NOT ADD PEOPLE YOU DON'T TRUST**
ownerIds:
- 105635123466156544
- 145521851676884992
- 341420590009417729
# The number of shards that the bot will running on.
# Leave at 1 if you don't know what you're doing.
totalShards: 1
# Login to https://console.cloud.google.com, create a new project, go to APIs & Services -> Library -> YouTube Data API and enable it.
# Then, go to APIs and Services -> Credentials and click Create credentials -> API key.
# Used only for Youtube Data Api (at the moment).
googleApiKey: 'AIzaSyDScfdfdfi1sdlWQOWxxxxxbk0oWMEzM'
# Settings for voting system for discordbots. Meant for use on global Nadeko.
votes:
url: ''
key: ''
# Patreon auto reward system settings.
# go to https://www.patreon.com/portal -> my clients -> create client
patreon:
# Access token. You have to manually update this 1st of each month by refreshing the token on https://patreon.com/portal
accessToken: ''
# Unused atm
refreshToken: ''
# Unused atm
clientSecret: ''
# Campaign ID of your patreon page. Go to your patreon page (make sure you're logged in) and type "prompt('Campaign ID', window.patreon.bootstrap.creator.data.id);" in the console. (ctrl + shift + i)
campaignId: ''
# Api key for sending stats to DiscordBotList.
botListToken: ''
# Official cleverbot api key.
cleverbotApiKey: ''
# Redis connection string. Don't change if you don't know what you're doing.
redisOptions: localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password=
# Database options. Don't change if you don't know what you're doing. Leave null for default values
db:
# Database type. Only sqlite supported atm
type: sqlite
# Connection string. Will default to "Data Source=data/NadekoBot.db"
connectionString: Data Source=data/NadekoBot.db
# Address and port of the coordinator endpoint. Leave empty for default.
# Change only if you've changed the coordinator address or port.
coordinatorUrl: http://localhost:3442
# Api key obtained on https://rapidapi.com (go to MyApps -> Add New App -> Enter Name -> Application key)
rapidApiKey: 4UrKpcWXcxxxxxxxxxxxxxxp1Q8kI6jsn32xxxoVWiY7
# https://locationiq.com api key (register and you will receive the token in the email).
# Used only for .time command.
locationIqApiKey:
# https://timezonedb.com api key (register and you will receive the token in the email).
# Used only for .time command
timezoneDbApiKey:
# https://pro.coinmarketcap.com/account/ api key. There is a free plan for personal use.
# Used for cryptocurrency related commands.
coinmarketcapApiKey:
# Api key used for Osu related commands. Obtain this key at https://osu.ppy.sh/p/api
osuApiKey: 4c8c8fdffdsfdsfsdfsfa33f3f3140a7d93320d6
# Command and args which will be used to restart the bot.
# Only used if bot is executed directly (NOT through the coordinator)
# placeholders:
# {0} -> shard id
# {1} -> total shards
# Linux default
# cmd: dotnet
# args: "NadekoBot.dll -- {0}"
# Windows default
# cmd: "NadekoBot.exe"
# args: "{0}"
restartCommand:
cmd:
args:
```
---
## Database
Nadeko saves all settings and data in the database file `NadekoBot.db`, located in:
- Windows (Updater): `system/data` (can be easily accessed through the `Data` button on the updater)
- Windows (Source), Linux and OSX: `nadekobot/output/data/NadekoBot.db`
In order to open it you will need [SQLite Browser](http://sqlitebrowser.org/).
*NOTE: You don't have to worry if you don't have the `NadekoBot.db` file, it gets automatically created once you successfully run the bot for the first time.*
**To make changes to the database on windows:**
- Shut your bot down.
- Copy the `NadekoBot.db` file to someplace safe. (Back up)
- Open it with SQLite Browser.
- Go to the **Browse Data** tab.
- Click on the **Table** drop-down list.
- Choose the table you want to edit.
- Click on the cell you want to edit.
- Edit it on the right-hand side.
- Click on **Apply**.
- Click on **Write Changes**.
![nadekodb](https://cdn.discordapp.com/attachments/251504306010849280/254067055240806400/nadekodb.gif)
---
## Sharding your bot
To run a sharded bot, you will want to run `src/NadekoBot.Coordinator` project.
Shards communicate with the coordinator using gRPC
To configure your Coordinator, you will need to edit the `src/NadekoBot.Coordinator/coord.yml` file
```yml
# total number of shards
TotalShards: 3
# How often do shards ping their state back to the coordinator
RecheckIntervalMs: 5000
# Command to run the shard
ShardStartCommand: dotnet
# Arguments to run the shard
# {0} = shard id
# {1} = total number of shards
ShardStartArgs: ../../output/NadekoBot.dll -- {0} {1}
# How long does it take for the shard to be forcefully restarted once it stops reporting its state
UnresponsiveSec: 30
```
[Google Console]: https://console.developers.google.com
[DiscordApp]: https://discordapp.com/developers/applications/me
[Invite Guide]: https://tukimoop.pw/s/guide.html

1
docs/md/CNAME Normal file
View File

@ -0,0 +1 @@
docs.wizbot.cc

View File

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

BIN
docs/md/assets/upeko-1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

BIN
docs/md/assets/upeko-2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
docs/md/assets/upeko-3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
docs/md/assets/upeko-4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
docs/md/assets/upeko-5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

32
docs/md/creds-guide.md Normal file
View File

@ -0,0 +1,32 @@
## Creating your own Discord bot
This guide will show you how to create your own discord bot, invite it to your server, and obtain the credentials needed to run it.
1. Go to [the Discord developer application page][DiscordApp].
2. Log in with your Discord account.
3. Click **New Application**.
4. Fill out the `Name` field however you like, accept the terms, and confirm.
5. Go to the **Bot** tab on the left sidebar.
6. Click on the `Add a Bot` button and confirm that you do want to add a bot to this app.
7. **Optional:** Add bot's avatar and description.
8. Copy your Token to `creds.yml` as shown above.
9. Scroll down to the **`Privileged Gateway Intents`** section
- You MUST enable the following:
- **PRESENCE INTENT**
- **SERVER MEMBERS INTENT**
- **MESSAGE CONTENT INTENT**
### Inviting your bot to your server
![Invite the bot to your server](https://cdn.wizbot.cc/tutorial/bot-invite-guide.gif)
- On the **General Information** tab, copy your `Application ID` from your [applications page][DiscordApp].
- Replace the `YOUR_CLIENT_ID_HERE` in this link:
`https://discordapp.com/oauth2/authorize?client_id=YOUR_CLIENT_ID_HERE&scope=bot&permissions=66186303` with your `Client ID`
- The link should now look something like this:
`https://discordapp.com/oauth2/authorize?client_id=123123123123&scope=bot&permissions=66186303`
- Access that newly created link, pick your Discord server, click `Authorize` and confirm with the captcha at the end
- The bot should now be in your server
[DiscordApp]: https://discordapp.com/developers/applications/me

View File

@ -1,16 +1,15 @@
# Donate
Nadeko is an [open-source project][gitlab], and we rely on your help to develop the bot, pay hosting fees, maintain our website and more.
WizBot is an [open-source project][github], and we rely on your help to develop the bot, pay hosting fees, maintain our website and more.
Donations go a long way in helping us keep the project alive, and we appreciate every single one of them.
## Perks
Donating to us also gives you the following benefits:
- A hoisted **Donators role** in our [Discord server][discord-server]
- A hoisted **Patron** role in [WizNet Discord server][discord-server]
- Access to exclusive **#noticed** text and voice channels
- **1000 flowers** on the public bot per dollar donated (after fees)
- **Custom Reactions** on the public bot for [Patreon pledges][patreon] of $5 or higher
- **3000 flowers** on the public bot per dollar donated (after fees)
## Patreon
@ -23,16 +22,16 @@ You can set up a monthly pledge on [Patreon][patreon] and support the project's
## PayPal
You can also donate to us through [PayPal][paypal] for one-time donations using the button below, or by donating to `nadekodiscordbot@gmail.com`.
You can also donate to us through [PayPal][paypal] for one-time donations using the button below.
!!! Note
Mention your Discord tag (Username#1234) in the payment note to receive flower rewards.
Mention your Discord username or user id in the payment note to receive flower rewards.
[![img][paypal-button]][paypal]
[gitlab]: https://gitlab.com/Kwoth/nadekobot
[discord-server]: https://discord.nadeko.bot/
[patreon]: https://www.patreon.com/nadekobot
[github]: https://github.com/Wizkiller96/WizBot
[discord-server]: https://wizbot.cc/discord
[patreon]: https://www.patreon.com/wiznet
[patreon-button]: ./assets/patreon.png
[paypal]: https://paypal.me/Kwoth
[paypal]: https://paypal.me/wizkiller96network
[paypal-button]: ./assets/paypal.png

232
docs/md/guides/cli-guide.md Normal file
View File

@ -0,0 +1,232 @@
# WizBot CLI Guide (via Bash Installer)
### Supported Operating Systems
--8<-- "md/snippets/supported-platforms.md:linux"
--8<-- "md/snippets/supported-platforms.md:macos"
### Prerequisites
macOS:
- [Homebrew](https://brew.sh/)
- [Curl](#__tabbed_1_5)
Linux:
- [Curl](#__tabbed_1_1)
---
??? note "24/7 Up-time via VPS (Digital Ocean Guide)"
--8<-- "md/guides/vps-linux-guide.md"
??? note "Creating a Discord Bot & Getting Credentials"
--8<-- "md/creds-guide.md"
---
## Installation Instructions
Open Terminal (if you're on an installation with a window manager) and navigate to the location where you want to install the bot (for example `cd ~`)
1. First make sure that curl is installed
/// tab | Ubuntu | Debian | Mint
```bash
sudo apt install curl
```
///
/// tab | Rocky | Alma | Fedora
```bash
sudo dnf install curl
```
///
/// tab | openSUSE
```bash
sudo zypper install curl
```
///
/// tab | Arch | Artix
```bash
sudo pacman -S curl
```
///
/// tab | macOS
```bash
brew install curl
```
///
2. Download and run the **new** installer script
``` sh
cd ~
curl -L -o n-install.sh https://raw.githubusercontent.com/Wizkiller96/bash-installer/refs/heads/v6/w-install.sh
bash w-install.sh
```
3. Install the bot (type `1` and press enter)
4. Edit creds (type `3` and press enter)
- *ALTERNATIVELY*, you can exit the installer (option `6`) and edit `wizbot/creds.yml` file yourself
5. Follow the instruction [below](#creating-your-own-discord-bot) to create your own Discord bot and obtain the credentials needed to run it.
- After you're done, you can close nano (and save the file) by inputting, in order:
- `CTRL` + `X`
- `Y`
- `Enter`
6. Run the installer script again
- `bash w-install.sh`
7. Run the bot (type `3` and press enter)
8. Done!
## Update Instructions
1. ⚠ Stop the bot ⚠
2. Navigate to your bot's folder, we'll use home directory as an example
- `cd ~`
3. Simply re-install the bot with a newer version by running the installer script
- `curl -L -o w-install.sh https://raw.githubusercontent.com/Wizkiller96/bash-installer/refs/heads/v6/w-install.sh && bash w-install.sh`
4. Select option 1, and select a NEWER version
## Running WizBot
There are two main methods to run WizBot: using `tmux` (macOS and Linux) or using `systemd` with a script (Linux only).
/// tab | Tmux (Preferred Method)
Using `tmux` is the simplest method, and is therefore recommended for most users.
!!! warning
Before proceeding, make sure your bot is not currently running by either running `.die` in your Discord server or exiting the process with `Ctrl+C`.
1. Access the directory where `w-install.sh` and `wizbot` is located.
2. Create a new tmux session: `tmux new -s wizbot`
- The above command will create a new session named **wizbot**. You may replace **wizbot** with any name you prefer.
3. Run the installer: `bash w-install.sh`
4. Start the bot by typing `3` and pressing `Enter`.
5. Detach from the tmux session, allowing the bot to run in the background:
- Press `Ctrl` + `B`
- Then press `D`
Now check your Discord server, the bot should be online. WizBot should now be running in the background of your system.
To re-open the tmux session to either update, restart, or whatever, execute `tmux a -t wizbot`. *(Make sure to replace "wizbot" with your session name. If you didn't change it, leave it as it is.)*
///
/// tab | Systemd
!!! note
Systemd is only available on Linux. macOS utilizes Launchd, which is not covered in this guide. If you're on macOS, please use the `tmux` method, or use [WizBot Updater](desktop-guide.md) to run WizBot.
This method is a bit more complex and involved, but comes with the added benefit of better error logging and control over what happens before and after the startup of WizBot.
1. Access the directory where `w-install.sh` and `wizbot` is located.
2. Use the following command to create a service that will be used to execute `WizBotRun.bash`:
```bash
echo "[Unit]
Description=WizBot service
After=network.target
StartLimitIntervalSec=60
StartLimitBurst=2
[Service]
Type=simple
User=$USER
WorkingDirectory=$PWD
ExecStart=/bin/bash WizBotRun.bash
#ExecStart=./wizbot/WizBot
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=WizBot
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/wizbot.service
```
3. Make the new service available: `sudo systemctl daemon-reload`
4. Use the following command to create a script that will be used to start WizBot:
```bash
cat <<EOF > WizBotRun.bash
#!/bin/bash
export PATH="$HOME/.local/bin:$PATH"
is_python3_installed=\$(command -v python3 &>/dev/null && echo true || echo false)
is_yt_dlp_installed=\$(command -v yt-dlp &>/dev/null && echo true || echo false)
[[ \$is_python3_installed == true ]] \\
&& echo "[INFO] python3 path: \$(which python3)" \\
&& echo "[INFO] python3 version: \$(python3 --version)"
[[ \$is_yt_dlp_installed == true ]] \\
&& echo "[INFO] yt-dlp path: \$(which yt-dlp)"
echo "[INFO] Running WizBot in the background with auto restart"
if [[ \$is_yt_dlp_installed == true ]]; then
yt-dlp -U || echo "[ERROR] Failed to update 'yt-dlp'" >&2
fi
echo "[INFO] Starting WizBot..."
while true; do
if [[ -d $PWD/wizbot ]]; then
cd "$PWD/wizbot" || {
echo "[ERROR] Failed to change working directory to '$PWD/wizbot'" >&2
echo "[INFO] Exiting..."
exit 1
}
else
echo "[WARN] '$PWD/wizbot' doesn't exist" >&2
echo "[INFO] Exiting..."
exit 1
fi
./WizBot || {
echo "[ERROR] An error occurred when trying to start WizBot" >&2
echo "[INFO] Exiting..."
exit 1
}
echo "[INFO] Waiting 5 seconds..."
sleep 5
if [[ \$is_yt_dlp_installed == true ]]; then
yt-dlp -U || echo "[ERROR] Failed to update 'yt-dlp'" >&2
fi
echo "[INFO] Restarting WizBot..."
done
echo "[INFO] Stopping WizBot..."
EOF
```
With everything set up, you can run WizBot in one of three modes:
1. **Auto-Restart Mode**: WizBot will restart automatically if you restart it via the `.die` command.
- To enable this mode, start the service: `sudo systemctl start wizbot`
2. **Auto-Restart on Reboot Mode**: In addition to auto-restarting after `.die`, WizBot will also start automatically on system reboot.
- To enable this mode, run:
```bash
sudo systemctl enable wizbot
sudo systemctl start wizbot
```
3. **Standard Mode**: WizBot will stop completely when you use `.die`, without restarting automatically.
- To switch to this mode:
1. Stop the service: `sudo systemctl stop wizbot`
2. Edit the service file: `sudo <editor> /etc/systemd/system/wizbot.service`
3. Modify the `ExecStart` line:
- **Comment out**: `ExecStart=/bin/bash WizBotRun.bash`
- **Uncomment**: `#ExecStart=./wizbot/WizBot`
4. Save and exit the editor.
5. Reload systemd: `sudo systemctl daemon-reload`
6. Disable automatic startup: `sudo systemctl disable wizbot`
7. Start WizBot manually: `sudo systemctl start wizbot`
///

View File

@ -0,0 +1,55 @@
# WizBot Desktop Guide (via Upeko)
### Supported Operating Systems
--8<-- "md/snippets/supported-platforms.md"
---
??? note "Creating a Discord Bot & Getting Credentials"
--8<-- "md/creds-guide.md"
---
## Setup
1. Download and run the [WizBot Updater](https://github.com/Wizkiller96/wizbot-updater/releases/latest).
![Create a new bot](../assets/upeko-1.png "Create a new bot")
2. Click the plus button to add a new bot
![Open bot page](../assets/upeko-2.png "Open bot page")
3. If you want to use the music module, click on **`Install`** next to `ffmpeg` and `yt-dlp` at the top
4. Click on the newly created bot
![Bot Setup](../assets/upeko-3.png "Bot Setup")
5. Click on **DOWNLOAD** at the lower right
![Download](../assets/upeko-4.png "Download")
![Creds](../assets/upeko-5.png "Edit creds")
6. When installation is finished, click on **`CREDS`** (`1`) above the **`RUN`** (`3`) button on the lower left
- **`2`** simply opens your bot's data folder.
7. Paste in your **BOT TOKEN** previously obtained
## Starting WizBot
- Either click on **`RUN`** button in the updater or run the bot via its desktop shortcut.
## Updating WizBot
!!! warning "IMPORTANT"
- Make sure WizBot is closed and not running
- Run `.die` in a connected server to make sure.
- Make sure you don't have `data` folder, bot folder, or any other bot file open in any program, as the updater will fail to replace your version
1. Run `upeko` if not already running
2. Click on your bot
3. Click on **`Check for updates`**
4. If updates are available, you will be able to click on the Update button
5. Click `Update`
6. Click `RUN` after it's done

View File

@ -0,0 +1,72 @@
# Docker Guide
### Prerequisites
- [Docker Core Engine](https://docs.docker.com/engine/install/)
- [Docker Compose](https://docs.docker.com/compose/install/) (optional, but recommended)
---
??? note "Creating a Discord Bot & Getting Credentials"
--8<-- "md/creds-guide.md"
---
## Installing WizBot with Docker
When deploying WizBot with Docker, you have two options: using [Docker](#__tabbed_1_1) or [Docker Compose](#__tabbed_1_2). The following sections provide step-by-step instructions for both methods.
/// tab | Docker
### Deploying WizBot with Docker
1. Move to a directory where you want your WizBot's data folder to be (data folder will keep the database and config files) and create a data folder there.
``` sh
cd ~ && mkdir wizbot && cd wizbot && mkdir data
```
2. Mount the newly created empty data folder as a volume while starting your docker container. Replace YOUR_TOKEN_HERE with the bot token obtained from the creds guide above.
``` 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
```
3. Enjoy! 🎉
### Updating your bot
If you want to update WizBot to the latest version, all you have to do is pull the latest image and re-run.
1. Pull the latest image
``` sh
docker pull ghcr.io/Wizkiller96/WizBot:v6
```
2. Re-run your bot the same way you did before
``` 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
```
3. Done! 🎉
///
/// tab | Docker Compose
1. **Choose Your Workspace:** Select a directory where you'll set up your WizBot stack. Use your terminal to navigate to this directory. For the purpose of this guide, we'll use `/opt/stacks/wizbot/` as an example, but you can choose any directory that suits your needs.
2. **Create a Docker Compose File:** In this directory, create a Docker Compose file named `docker-compose.yml`. You can use any text editor for this task. For instance, to use the `nano` editor, type `nano docker-compose.yml`.
3. **Configure Your Docker Compose File:** Populate your Docker Compose file with the following configuration:
``` yml
services:
wizbot:
image: ghcr.io/Wizkiller96/WizBot:v6
container_name: wizbot
restart: unless-stopped
environment:
TZ: Europe/Rome # Modify this to your timezone
bot_token: YOUR_TOKEN_HERE
volumes:
- /opt/stacks/wizbot/data:/app/data
networks: {}
```
1. **Launch Your Bot:** Now, you're ready to run Docker Compose. Use the following command: `docker compose up -d`.
2. **Navigate to Your Directory:** Use `cd /opt/stacks/wizbot/` to go to the directory containing your Docker Compose file.
3. **Pull the Latest Images:** Use `docker compose pull` to fetch the latest images.
4. **Restart Your Containers:** Use `docker compose up -d` to restart the containers.
///

View File

@ -0,0 +1,66 @@
# Setting Up WizBot on Windows from source
### Prerequisites
- Windows 10 or later (64-bit)
- [.net 8 sdk](https://dotnet.microsoft.com/download/dotnet/8.0)
- If you want wizbot to play music: [Visual C++ 2010 (x86)] and [Visual C++ 2017 (x64)] (both are required, you may install them later)
- [git](https://git-scm.com/downloads) - needed to clone the repository (you can also download the zip manually and extract it, but this guide assumes you're using git)
- **Optional** Any code editor, for example [Visual Studio Code](https://code.visualstudio.com/Download)
- You'll need to at least modify creds.yml, notepad is inadequate
---
??? note "Creating a Discord Bot & Getting Credentials"
--8<-- "md/creds-guide.md"
---
## Installation Instructions
Open PowerShell (press windows button on your keyboard and type powershell, it should show up; alternatively, right click the start menu and select Windows PowerShell), and
1. Navigate to the location where you want to install the bot
- for example, type `cd ~/Desktop/` and press enter
2. `git clone https://github.com/Wizkiller96/WizBot -b v6 --depth 1`
3. `cd wizbot/src/WizBot`
4. `dotnet build -c Release`
5. `cp data/creds_example.yml data/creds.yml`
6. "You're done installing, you may now proceed to set up your bot's credentials by following the [#creds-guide]
- Once done, come back here and run the last command
6. Run the bot `dotnet WizBot.dll`
7. 🎉 Enjoy
## Update Instructions
Open PowerShell as described above and run the following commands:
1. Stop the bot
- ⚠️ Make sure you don't have your database, credentials or any other wizbot folder open in some application, this might prevent some of the steps from executing successfully
2. Navigate to your bot's folder, example:
- `cd ~/Desktop/wizbot`
3. Pull the new version, and make sure you're on the v6 branch
- `git pull`
- ⚠️ IF this fails, you may want to `git stash` or remove your code changes if you don't know how to resolve merge conflicts
4. **Backup** old output in case your data is overwritten
- `cp -r -fo output/ output-old`
5. Build the bot again
- `dotnet run -c Release src/WizBot/`
6. Copy old data, and new strings
- `cp -r -fo .\output-old\data\ .\output\`
7. Run the bot
- `cd output`
- `dotnet WizBot.dll`
8. 🎉 Enjoy
## Music Prerequisites
In order to use music commands, you need ffmpeg and yt-dlp installed.
- [ffmpeg]
- [yt-dlp]
- Click to download the `yt-dlp.exe` file, then move `yt-dlp.exe` to a path that's in your PATH environment variable. If you don't know what that is, just move the `yt-dlp.exe` file to your wizbot's output folder.
[.net]: https://dotnet.microsoft.com/download/dotnet/8.0
[ffmpeg]: https://github.com/GyanD/codexffmpeg/releases/latest
[yt-dlp]: https://github.com/yt-dlp/yt-dlp/releases/latest

View File

@ -0,0 +1,54 @@
## Setting up WizBot on a Linux VPS (Digital Ocean Droplet)
If you want WizBot to play music for you 24/7 without having to hosting it on your PC and want to keep it cheap, reliable and convenient as possible, you can try WizBot on Linux Digital Ocean Droplet using the link [DigitalOcean](https://m.do.co/c/7290047d0c84) (by using this link, you will get **$10 credit** and also support WizBot)
To set up the VPS, please select the options below
```
These are the min requirements you must follow:
OS: Any between Ubuntu, Fedora, and Debian
Droplet Type: SHARED CPU | Basic
CPU options: Regular | Disk type: SSD
6$/mo
1 GB / 1 CPU
25 GB SSD Disk
1000 GB transfer
Note: You can select the cheapest option with 512 MB / 1 CPU but this has been a hit or miss.
Datacenter region: Choose one depending on where you are located.
Authentication: Password or SSH
(Select SSH if you know what you are doing, otherwise choose password)
Click create droplet
```
**Setting up WizBot**
Assuming you have followed the link above to setup an account and a Droplet with a 64-bit operational system on Digital Ocean and got the `IP address and root password (in your e-mail)` to login, it's time to get started.
**This section is only relevant to those who want to host WizBot on DigitalOcean. Go through this whole section before setting the bot up.**
### Prerequisites
- Download [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html)
- Download [WinSCP](https://winscp.net/eng/download.php) *(optional)*
- [Create and invite the bot](../creds-guide.md).
### Starting up
- **Open PuTTY** and paste or enter your `IP address` and then click **Open**.
If you entered your Droplets IP address correctly, it should show **login as:** in a newly opened window.
- Now for **login as:**, type `root` and press enter.
- It should then ask for a password. Type the `root password` you have received in your e-mail address, then press Enter.
If you are running your droplet for the first time, it will most likely ask you to change your root password. To do that, copy the **password you've received by e-mail** and paste it on PuTTY.
- To paste, just right-click the window (it won't show any changes on the screen), then press Enter.
- Type a **new password** somewhere, copy and paste it on PuTTY. Press Enter then paste it again.
**Save the new password somewhere safe.**
After that, your droplet should be ready for use.
[Setting up WizBot on a VPS (Digital Ocean)]: #setting-up-wizbot-on-a-linux-vps-digital-ocean-droplet

40
docs/md/index.md Normal file
View File

@ -0,0 +1,40 @@
# WizBot Documentation
<!-- ![img][header] -->
## Inviting WizBot
There are two versions of WizBot, a public bot and a self-hostable bot.
To invite public WizBot to your server or to view its commands, click on the buttons below:
[:material-plus: Add WizBot to your server][invite]{ .md-button .md-button--primary }
[:material-format-list-text: View commands][commands]{ .md-button }
To self-host your own WizBot, use the guides below:
- [:material-television-guide: Desktop guide (Windows/Linux/macOS)][desktop-guide]
- [:material-console: CLI guide (Linux/macOS)][cli-guide]
- [:material-docker: Docker guide][docker-guide]
- [:material-source-branch: From source guide][from-source-guide]
In case you need any help, join our [Discord server][discord-server] where we may provide support.
## About WizBot
WizBot is an [open source project][github]. Any issues with the bot may be filed [here][issues].
If you're unsure whether something is an issue, ask in our support server first.
[Donations are welcome][donate], and we rely on your contributions to help keep the project alive.
[invite]: https://wizbot.cc/botinvite
[commands]: https://wizbot.cc/commands
[desktop-guide]: ./guides/desktop-guide.md
[cli-guide]: ./guides/cli-guide.md
[docker-guide]: ./guides/docker-guide.md
[from-source-guide]: ./guides/source-guide.md
[discord-server]: https://wizbot.cc/discord
[github]: https://github.com/Wizkiller96/WizBot
[issues]: https://github.com/Wizkiller96/WizBot/issues
[donate]: ./donate.md

View File

@ -0,0 +1,164 @@
# Creating A Medusa
## Getting started
This section will guide you through how to create a simple custom medusa. You can find the entirety of this code hosted [here](https://gitlab.com/WizNet/example_medusa)
## Prerequisite
- [.net8 sdk](https://dotnet.microsoft.com/en-us/download) installed
- Optional: use [vscode](https://code.visualstudio.com/download) to write code
## Guide
- Open your favorite terminal and navigate to a folder where you will keep your project .
- Create a new folder and move into it
- `mkdir example_medusa `
- `cd example_medusa`
- Install wiz-medusa template
- `dotnet new install wiz-medusa`
- Make a new Wiz Medusa project
- `dotnet new wiz-medusa`
## Build it
- Build your Medusa into a dll that Wiz can load. In your terminal, type:
- `dotnet publish -o bin/medusae/example_medusa /p:DebugType=embedded`
- Done. You can now try it out in action.
## Try it out
- Copy the `bin/medusae/example_medusa` folder into your WizBot's `data/medusae/` folder. (WizBot version 4.1.0+)
- Load it with `.meload example_medusa`
- In the channel your bot can see, run the following commands to try it out
- `.hello` and
- `.hello @<someone>`
- Check its information with
- `.meinfo example_medusa`
- Unload it
- `.meunload example_medusa`
- :tada: Congrats! You've just made your first medusa! :tada:
## Theory
Medusa system allows you to write independent medusae (known as "modules", "cogs" or "plugins" in other software) which you can then load, unload and update at will without restarting the bot.
The system itself borrows some design from the current way Wiz's Modules are written but mostly from never-released `Ayu.Commands` system which was designed to be used for a full WizBot v3 rewrite.
The medusa base classes used for development are open source [here](https://github.com/Wizkiller96/WizBot/tree/v6/src/Wiz.Medusa) in case you need reference, as there is no generated documentation at the moment.
## Term list
### Medusa
- The project itself which compiles to a single `.dll` (and some optional auxiliary files), it can contain multiple [Sneks](#snek), [Services](#service), and [ParamParsers](#param-parser)
### Snek
- A class which will be added as a single Module to WizBot on load. It also acts as a [lifecycle handler](snek-lifecycle.md) and as a singleton service with the support for initialize and cleanup.
- It can contain a Snek (called SubSnek) but only 1 level of nesting is supported (you can only have a snek contain a subsnek, but a subsnek can't contain any other sneks)
- Sneks can have their own prefix
- For example if you set this to 'test' then a command called 'cmd' will have to be invoked by using `.test cmd` instead of `.cmd`
### Snek Command
- Acts as a normal command
- Has context injected as a first argument which controls where the command can be executed
- `AnyContext` the command can be executed in both DMs and Servers
- `GuildContext` the command can only be executed in Servers
- `DmContext` the command can only be executed in DMs
- Support the usual features such as default values, leftover, params, etc.
- It also supports dependency injection via `[inject]` attribute. These dependencies must come after the context and before any input parameters
- Supports `ValueTask`, `Task`, `Task<T>` and `void` return types
### Param Parser
- Allows custom parsing of command arguments into your own types.
- Overriding existing parsers (for example for IGuildUser, etc...) can cause issues.
### Service
- Usually not needed.
- They are marked with a `[svc]` attribute, and offer a way to inject dependencies to different parts of your medusa.
- Transient and Singleton lifetimes are supported.
### Localization
Response and command strings can be kept in one of three different places based on whether you plan to allow support for localization
option 1) `res.yml` and `cmds.yml`
If you don't plan on having your app localized, but you just *may* in the future, you should keep your strings in the `res.yml` and `cmds.yml` file the root folder of your project, and they will be automatically copied to the output whenever you build your medusa.
**Example project folder structure:**
- uwu/
- uwu.csproj
- uwu.cs
- res.yml
- cmds.yml
**Example output folder structure:**
- medusae/uwu/
- uwu.dll
- res.yml
- cmds.yml
option 2) `strings` folder
If you plan on having your app localized (or want to allow your consumers to easily add languages themselves), you should keep your response strings in the `strings/res/en-us.yml` and your command strings in `strings/cmds/en-us.yml` file. This will be your base file, and from there you can make support for additional languages, for example `strings/res/ru-ru.yml` and `strings/cmds/ru-ru.yml`
**Example project folder structure:**
- uwu/
- uwu.csproj
- uwu.cs
- strings/
- res/
- en-us.yml
- ru-ru.yml
- cmds/
- en-us.yml
- ru-ru.yml
**Example output folder structure:**
- medusae/uwu/
- uwu.dll
- strings/
- res/
- en-us.yml
- ru-ru.yml
- cmds/
- en-us.yml
- ru-ru.yml
option 3) In the code
If you don't want any auxiliary files, and you don't want to bother making new .yml files to keep your strings in, you can specify the command strings directly in the `[cmd]` attribute itself, and use non-localized methods for message sending in your commands.
If you update your response strings .yml file(s) while the medusa is loaded and running, running `.stringsreload` will reload the responses without the need to reload the medusa or restart the bot.
### Bot medusa config file
- Medusa config is kept in `data/medusae/medusa.yml` file in WizBot installation folder
- At the moment this config only keeps track of which medusae are currently loaded (they will also be always loaded at startup)
- If a medusa is causing issues and you're unable to unload it, you can remove it from the `loaded:` list in this config file and restart the bot. It won't be loaded next time the bot is started up
### Unloadability issues
To make sure your medusa can be properly unloaded/reloaded you must:
- Make sure that none of your types and objects are referenced by the Bot or Bot's services after the DisposeAsync is called on your Snek instances.
- Make sure that all of your commands execute quickly and don't have any long running tasks, as they will hold a reference to a type from your assembly
- If you are still having issues, you can always run `.meunload` followed by a bot restart, or if you want to find what is causing the medusa unloadability issues, you can check the [microsoft's assembly unloadability debugging guide](https://docs.microsoft.com/en-us/dotnet/standard/assembly/unloadability)

View File

@ -0,0 +1,30 @@
# Getting Started
## What is the Medusa system?
- It is a dynamic module/plugin/cog system for WizBot introduced in **WizBot 4.1.0**
- Allows developers to add custom functionality to Wiz without modifying the original code
- Allows for those custom features to be updated during bot runtime (if properly written), without the need for bot restart.
- They are added to `data/medusae` folder and are loaded, unloaded and handled through discord commands.
- `.meload` Loads the specified medusa (see `.h .meload`)
- `.meunload` Unloads the specified medusa (see `.h .meunload`)
- `.meinfo` Checks medusae information (see `.h .meinfo`)
- `.melist` Lists the available medusae (see `.h .melist`)
## How to make one?
Medusae are written in [C#](https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/) programming language, so you will need at least low-intermediate knowledge of it in order to make a useful Medusa.
Follow the [creating a medusa guide](creating-a-medusa.md)
## Where to get medusae other people made?
*It is EXTREMELY, and I repeat **EXTREMELY** dangerous to run medusae of strangers or people you don't FULLY trust.* ⚠
*It can not only lead to your bot being stolen, but it also puts your entire computer and personal files in jeopardy.*
**It is strongly recommended to run only the medusae you yourself wrote, and only on a hosted VPS or dedicated server which ONLY hosts your bot, to minimize the potential damage caused by bad actors.**
No easy way at the moment, except asking in the `#dev-and-modding` chat in [WizNet server](https://wizbot.cc/discord)

View File

@ -0,0 +1,15 @@
# Snek Lifecycle
*You can override several methods to hook into command handler's lifecycle.
These methods start with `Exec*`*
- `ExecOnMessageAsync` runs first right after any message was received
- `ExecInputTransformAsync` runs after ExecOnMessageAsync and allows you to transform the message content before the bot looks for the matching command
- `ExecPreCommandAsync` runs after a command was found but not executed, allowing you to potentially prevent command execution
- `ExecPostCommandAsync` runs if the command was successfully executed
- `ExecOnNoCommandAsync` runs instead of ExecPostCommandAsync if no command was found for a message
*Besides that, sneks have 2 methods with which you can initialize and cleanup your snek*
- `InitializeAsync` Runs when the medusa which contains this snek is being loaded
- `DisposeAsync` Runs when the medusa which contains this snek is being unloaded

View File

@ -0,0 +1,18 @@
<!-- TODO: These should potentially be reformated to be more readable... -->
--8<-- [start:windows]
- **Windows 10** or later (64-bit)
--8<-- [end:windows]
--8<-- [start:linux]
- **Ubuntu**: 20.04, 22.04, 24.04
- **Mint**: 19, 20, 21
- **Debian**: 10, 11, 12
- **RockyLinux**: 8, 9
- **AlmaLinux**: 8, 9
- **openSUSE Leap**: 15.5, 15.6
- **openSUSE Tumbleweed**
- **Fedora**: 38, 39, 40, 41, 42
- **Arch** & **Artix**
--8<-- [end:linux]
--8<-- [start:macos]
- **macOS 13 (Ventura)** or later
--8<-- [end:macos]

View File

@ -3,7 +3,7 @@
/* general styling changes */
.md-typeset * {
.md-typeset * {
letter-spacing: 0 !important;
}
@ -119,4 +119,4 @@ hr+h1, hr+h2, hr+h3, hr+h4, hr+h5, hr+h6 {
.admonition * {
font-size: .75rem;
}
}

View File

@ -0,0 +1,85 @@
[data-md-color-scheme="wizbot-dark"] {
/* Default color shades */
--md-primary-fg-color: #590074;
--md-primary-fg-color--light: #964aad;
--md-primary-fg-color--dark: #964aad;
--md-default-bg-color: #0b0b0b;
--md-default-bg-color--light: #e8e8e8;
--md-default-fg-color: hsla(0, 75%, 95%, 1);
--md-default-fg-color--light: hsla(0, 0%, 100%, 0.849);
--md-default-fg-color--lighter: hsla(0, 0%, 100%, 0.32);
--md-default-fg-color--lightest: hsla(0, 0%, 100%, 0.12);
--md-accent-fg-color: #964aad !important;
--md-typeset-color: var(--md-default-fg-color);
--md-typeset-a-color: #964aad !important;
--md-typeset-mark-color: #448aff;
--md-typeset-kbd-color: hsla(220, 10%, 94%, 0.12);
--md-typeset-kbd-accent-color: hsla(220, 10%, 94%, 0.2);
--md-typeset-kbd-border-color: hsla(220, 10%, 14%, 1);
--md-admonition-bg-color: hsla(220, 10%, 100%, 0.025);
--md-admonition-fg-color: hsla(0, 75%, 95%, 1);
/* Code Color Shade */
--md-code-fg-color: rgb(255, 255, 255);
--md-code-bg-color: rgb(39, 39, 39);
--md-code-hl-color: rgb(255, 255, 0);
--md-code-hl-number-color: rgb(235, 88, 88);
--md-code-hl-special-color: rgb(241, 104, 150);
--md-code-hl-function-color: rgb(168, 70, 185);
--md-code-hl-constant-color: rgb(110, 89, 217);
--md-code-hl-keyword-color: rgb(63, 110, 198);
--md-code-hl-string-color: rgb(64, 168, 116);
--md-code-hl-name-color: rgb(54, 70, 78);
--md-code-hl-operator-color: rgba(255, 255, 255, 0.54);
--md-code-hl-punctuation-color: rgba(255, 255, 255, 0.54);
--md-code-hl-comment-color: rgba(255, 255, 255, 0.54);
--md-code-hl-generic-color: rgba(255, 255, 255, 0.54);
--md-code-hl-variable-color: rgba(255, 255, 255, 0.54);
/* Footer color shades */
--md-footer-bg-color: rgb(43, 44, 46) !important;
--md-footer-bg-color--dark: rgb(25, 26, 27) !important;
}
[data-md-color-scheme="wizbot-light"] {
/* Default color shades */
--md-primary-fg-color: #590074;
--md-primary-fg-color--light: #964aad;
--md-primary-fg-color--dark: #964aad;
--md-default-bg-color: #e8e8e8;
--md-default-bg-color--light: #e8e8e8;
--md-default-fg-color: hsla(0, 0%, 0%, 1.5);
--md-default-fg-color--light: hsla(0deg, 0%, 0%, 85%);
--md-default-fg-color--lighter: hsla(0deg, 0%, 100%, 32%);
--md-default-fg-color--lightest: hsla(0deg, 0%, 100%, 12%);
--md-accent-fg-color: #964aad !important;
--md-typeset-color: var(--md-default-fg-color);
--md-typeset-a-color: #964aad !important;
--md-typeset-mark-color: #448aff;
--md-typeset-kbd-color: hsla(220, 10%, 94%, 0.12);
--md-typeset-kbd-accent-color: hsla(220, 10%, 94%, 0.2);
--md-typeset-kbd-border-color: hsla(220, 10%, 14%, 1);
--md-admonition-bg-color: hsla(220, 10%, 100%, 0.025);
--md-admonition-fg-color: rgba(0, 0, 0, 0.712);
/* Code Color Shade */
--md-code-fg-color: rgb(255, 255, 255);
--md-code-bg-color: rgb(39, 39, 39);
--md-code-hl-color: rgb(255, 255, 0);
--md-code-hl-number-color: rgb(235, 88, 88);
--md-code-hl-special-color: rgb(241, 104, 150);
--md-code-hl-function-color: rgb(168, 70, 185);
--md-code-hl-constant-color: rgb(110, 89, 217);
--md-code-hl-keyword-color: rgb(63, 110, 198);
--md-code-hl-string-color: rgb(64, 168, 116);
--md-code-hl-name-color: rgb(54, 70, 78);
--md-code-hl-operator-color: rgba(255, 255, 255, 0.54);
--md-code-hl-punctuation-color: rgba(255, 255, 255, 0.54);
--md-code-hl-comment-color: rgba(255, 255, 255, 0.54);
--md-code-hl-generic-color: rgba(255, 255, 255, 0.54);
--md-code-hl-variable-color: rgba(255, 255, 255, 0.54);
/* Footer color shades */
--md-footer-bg-color: rgb(43, 44, 46) !important;
--md-footer-bg-color--dark: rgb(25, 26, 27) !important;
}

View File

@ -0,0 +1,3 @@
mkdocs-material~=9.6
mkdocs~=1.6
mkdocs-exclude~=1.0

86
docs/mkdocs.yml Normal file
View File

@ -0,0 +1,86 @@
site_name: 'WizBot'
site_url: 'https://wizbot.cc'
repo_url: 'https://github.com/Wizkiller96/WizBot'
site_author: 'WizNet'
docs_dir: 'md'
copyright: © Copyright 2025 WizNet - All Rights Reserved.
theme:
name: material
palette:
- media: "(prefers-color-scheme: light)"
scheme: wizbot-light
toggle:
icon: material/weather-sunny
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: wizbot-dark
toggle:
icon: material/weather-night
name: Switch to light mode
features:
- navigation.instant
- navigation.expand
- navigation.top
font:
text: Source Sans Pro
code: Source Code Pro
logo: https://wizbot.cc/img/wizbot-icon-887x889.png
favicon: https://wizbot.cc/img/wizbot-icon-887x889.png
icon:
repo: material/github
extra:
homepage: https://wizbot.cc
extra_javascript:
- https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js
extra_css:
- https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css
- stylesheets/styling-overrides.css
- stylesheets/theme.css
plugins:
- search
- exclude:
glob:
- 'guides/vps-linux-guide.md'
- 'snippets/supported-platforms.md'
markdown_extensions:
- attr_list
- codehilite:
guess_lang: false
- toc:
permalink: true
- pymdownx.betterem:
smart_enable: all
- admonition
- pymdownx.inlinehilite
- pymdownx.superfences
- pymdownx.blocks.tab:
alternate_style: true
- pymdownx.snippets
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
nav:
- Home: index.md
- Guides:
- Desktop Guide: guides/desktop-guide.md
- CLI Guide: guides/cli-guide.md
- Docker Guide: guides/docker-guide.md
- Source Guide: guides/source-guide.md
- Commands:
- Commands List: https://wizbot.cc/commands
- Features Explained:
- Basic Creds: creds-guide.md
- Medusa System:
- medusa/getting-started.md
- medusa/creating-a-medusa.md
- medusa/snek-lifecycle.md
- Donate: donate.md

View File

@ -1,9 +0,0 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0071 23.007L16.4231 9.41602H7.59106L12.0071 23.007Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.007 23.007L7.59101 9.41602H1.4021L12.007 23.007Z" fill="white" fill-opacity="0.66"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.40214 9.41602L0.0601964 13.5462C-0.0622036 13.9229 0.0718535 14.3356 0.39231 14.5684L12.007 23.007L1.40214 9.41602Z" fill="white" fill-opacity="0.33"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.4021 9.41592H7.59101L4.93124 1.23021C4.79444 0.80895 4.19856 0.809064 4.06176 1.23021L1.4021 9.41592Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.0071 23.007L16.4231 9.41602H22.612L12.0071 23.007Z" fill="white" fill-opacity="0.66"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M22.612 9.41602L23.9539 13.5462C24.0763 13.9229 23.9423 14.3356 23.6218 14.5684L12.0071 23.007L22.612 9.41602Z" fill="white" fill-opacity="0.33"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M22.612 9.41592H16.4231L19.0829 1.23021C19.2197 0.80895 19.8156 0.809064 19.9524 1.23021L22.612 9.41592Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -1,94 +0,0 @@
# Permissions Overview
Have you ever felt confused or even overwhelmed when trying to set Nadeko's permissions? In this guide we will be explaining **how to use the permission commands correctly** and even **cover a few common questions**! Every command we discuss here can be found in the [Commands List].
## Why do we use the Permissions Commands?
Permissions are very handy at setting who can use what commands in a server. All commands and modules are enabled by default. If something is a bot owner only command, it can only be ran by the bot owner, the person who is running the bot, or has their ID in the [creds.yml](creds-guide.md) file.
Several commands still require that you have the correct permissions on Discord to be able to use them, so for users to be able to use commands like `.kick` and `.voicemute`, they need **Kick** and **Mute Members** server permissions, respectively.
With the permissions system it possible to restrict who can skip the current song, pick NadekoFlowers or use the NSFW module.
## First Time Setup
To change permissions you **must** meet the following requirements:
**Have Administrator Server Permission.**
**If you are NOT the server owner or an admin, get the role set to `.permrole` (there is no permission role by default).**
## Basics & Hierarchy
The [Commands List] is a great tool which lists **all** available commands, however we'll go over a few of them here.
First, let's explain how the permissions system works - It's simple once you figure out how each command works!
The permissions system works as a chain. Everytime a command is used, the permissions chain is checked. Starting from the top of it, the command is compared to a rule, if it isn't either allowed or disallowed by that rule it proceeds to check the next rule all the way till it reaches the bottom rule, which allows all commands.
To view this permissions chain, do `.lp`. The rule at the top of the chain takes priority over all rules below it.
If you want to remove a permission from the chain of permissions, do `.rp X` to remove rule number X and similarly, do `.mp X Y` to move rule number X to number Y (moving, not swapping!).
If you want the bot to notify users why they can't use a command or module, use `.verbose true` and Nadeko will tell you what rule is preventing the command from being used.
## Commonly Asked Questions
#### How do I restrict all commands to a single channel?
To allow users to only use commands in a specific text channel, follow these steps:
1. `.asm disable`
- Disables all modules on the entire server
2. `.acm enable #bot-spammerino`
- Enables all modules in the #bot-spammerino channel
#### How do I allow only one module to be used in a specific channel?
To allow users to only use commands from a certain module, let's say **gambling**, in a specific text channel, follow these steps:
1. `.acm disable #gamblers-den`
- Disables all modules in the #gamblers-den channel
2. `.cm Gambling enable #gamblers-den`
- Enables usage of the Gambling module in the #gamblers-den channel
#### How do I create a music DJ?
To allow users to only see the current song and have a DJ role for queuing follow these steps:
1. `.sm Music disable`
- Disables music commands for everybody
2. `.sc .nowplaying enable`
- Enables the "nowplaying" command for everyone
3. `.sc .listqueue enable`
- Enables the "listqueue" command for everyone
4. `.rm Music enable DJ`
- Enables all music commands only for the DJ role
#### How do I create a NSFW role?
Say you want to only enable NSFW commands for a specific role, just do the following two steps.
1. `.sm NSFW disable`
- Disables the NSFW module from being used
2. `.rm NSFW enable Lewd`
- Enables usage of the NSFW module for the Lewd role
#### How do I disable custom reactions from triggering?
If you don't want server or global custom reactions, just block the module that controls their usage:
1. `.sm ActualCustomReactions disable`
- Disables the ActualCustomReactions module from being used
**Note**: The `ActualCustomReactions` module controls the usage of custom reactions. The `CustomReactions` module controls commands related to custom reactions (such as `.acr`, `.lcr`, `.crca`, etc).
#### I've broken permissions and am stuck, can I reset permissions?
Yes, there is a way, in one easy command!
1. `.resetperms`
- This resets the permission chain back to default
*-- Thanks to @applemac for providing the template for this guide*
[Commands List]: https://nadeko.bot/commands

View File

@ -1,94 +0,0 @@
# Placeholders
Placeholders are used in Quotes, Custom Reactions, Greet/Bye messages, playing statuses, and a few other places.
They can be used to make the message more user friendly, generate random numbers or pictures, etc.
Some features have their own specific placeholders which are noted in that feature's command help. Some placeholders are not available in certain features because they don't make sense there.
## Usual placeholders
!!! Note
If you're using placeholders in embeds, don't use %user.mention% and %bot.mention% in titles, footers and field names. They will not show properly.
### Bot placeholders
- `%bot.status%` - Bot's status (Online, Idle, DoNotDisturb, Invisible)
- `%bot.latency%` - Bot latency
- `%bot.name%` - Bot username
- `%bot.mention%` - Bot mention (clickable)
- `%bot.fullname%` - Bot username#discriminator
- `%bot.time%` - Bot time (usually the time of the server it's hosted on)
- `%bot.discrim%` - Bot's discriminator
- `%bot.id%` - Bot's user ID
- `%bot.avatar%` - Bot's avatar url
### Server placeholders
- `%server.id%` - Server ID
- `%server.name%` - Server name
- `%server.members%` - Member count
- `%server.time%` - Server time (requires `.timezone` to be set)
### Channel placeholders
- `%channel.mention%` - Channel mention (clickable)
- `%channel.name%` - Channel name
- `%channel.id%` - Channel ID
- `%channel.created%` - Channel creation date
- `%channel.nsfw%` - Returns either `True` or `False`, depending on if the channel is designated as NSFW using discord
- `%channel.topic%` - Channel topic
### User placeholders
- `%user.mention%` - User mention
- `%user.fullname%` - Username#discriminator
- `%user.name%` - Username
- `%user.discrim%` - Discriminator
- `%user.avatar%` - User's avatar url
- `%user.id%` - User ID
- `%user.created_time%` - Account creation time (local time)
- `%user.created_date%` - Account creation date
- `%user.joined_time%` - Account join time (local time)
- `%user.joined_date%` - Account join date
### Ban message placeholders
- `%ban.mod%` - Full name of the moderator who performed the ban
- `%ban.mod.fullname%` - Full name of the moderator who performed the ban
- `%ban.mod.mention%` - Moderator's mention
- `%ban.mod.name%` - Name of the moderator - Admin
- `%ban.mod.discrim%` - Discriminator of the moderator - 1234
- `%ban.user%` - Full name of the banned user
- `%ban.user.fullname%` - Full name of the banned user
- `%ban.user.name%` - Name of the banned user
- `%ban.user.discrim%` - Discriminator of the banned user
- `%ban.reason%` - Reason for the ban, if provided
- `%ban.duration%` - Duration of the ban in the form Days.Hours:Minutes (6.05:04)
### Bot stats placeholders
- `%servers%` - Server count bot has joined
- `%users%` - Combined user count on servers the bot has joined
### Shard stats placeholders
- `%shard.servercount%` - Server count on current shard
- `%shard.usercount%` - Combined user count on current shard
- `%shard.id%` - Shard ID
### Music placeholders
!!! Note
These placeholders will only work in rotating playing statuses.
- `%music.queued%` - Amount of songs currently queued
- `%music.playing%` - Current song name
### Miscellaneous placeholders
- `%rngX-Y%` - Returns a random number between X and Y
- `%target%` - Returns anything the user has written after the trigger (only works on custom reactions)
- `%img:stuff%` - Returns an `imgur.com` search for "stuff" (only works on custom reactions)
![img](https://puu.sh/B7mgI.png)

View File

@ -1,54 +0,0 @@
[data-md-color-scheme="dark"] {
--md-default-fg-color: hsl(220, 10%, 100%);
--md-default-fg-color--light: hsl(220, 10%, 87%);
--md-default-fg-color--lighter: hsl(220, 10%, 54%);
--md-default-fg-color--lightest: hsl(220, 10%, 32%);
--md-default-bg-color: hsl(220, 10%, 20%);
--md-default-bg-color--light: hsl(220, 10%, 16%);
--md-default-bg-color--lighter: hsl(220, 10%, 12%);
--md-default-bg-color--lightest: hsl(220, 10%, 8%);
--md-code-fg-color: hsla(220, 10%, 86%, 1);
--md-code-bg-color: hsla(220, 10%, 15%, 1);
--md-code-hl-color: #448aff;
--md-code-hl-number-color: #e6695b;
--md-code-hl-special-color: #f06090;
--md-code-hl-function-color: #c973d9;
--md-code-hl-constant-color: #9383e2;
--md-code-hl-keyword-color: #6791e0;
--md-code-hl-string-color: #2fb170;
--md-code-hl-name-color: var(--md-code-fg-color);
--md-code-hl-operator-color: var(--md-default-fg-color--light);
--md-code-hl-punctuation-color: var(--md-default-fg-color--light);
--md-code-hl-comment-color: var(--md-default-fg-color--light);
--md-code-hl-generic-color: var(--md-default-fg-color--light);
--md-code-hl-variable-color: var(--md-default-fg-color--light);
--md-typeset-color: var(--md-default-fg-color);
--md-typeset-a-color: var(--md-primary-fg-color);
--md-typeset-mark-color: #448aff;
--md-typeset-kbd-color: hsla(220, 10%, 94%, 0.12);
--md-typeset-kbd-accent-color: hsla(220, 10%, 94%, 0.2);
--md-typeset-kbd-border-color: hsla(220, 10%, 14%, 1);
--md-admonition-bg-color: hsla(220, 10%, 100%, 0.025);
--md-footer-bg-color: hsl(220, 10%, 16%);
--md-footer-bg-color--dark: hsl(220, 10%, 12%);
}
[data-md-color-scheme="dark"] .md-typeset {
color: var(--md-default-fg-color--light);
}
[data-md-color-scheme="dark"][data-md-color-primary="black"], [data-md-color-scheme="dark"][data-md-color-primary="white"] {
--md-typeset-a-color: var(--md-accent-fg-color);
}
[data-md-color-scheme="dark"] .md-header {
background: var(--md-default-bg-color--light);
}
[data-md-color-scheme="dark"] .md-nav__item :not(.md-nav__link--active) {
color: var(--md-default-fg-color--light);
}
[data-md-color-scheme="dark"] .md-nav__item .md-nav__link:hover {
color: var(--md-primary-fg-color);
}

View File

@ -1,74 +0,0 @@
#define sysfolder "system"
#define version GetEnv("NADEKOBOT_INSTALL_VERSION")
#define target "win7-x64"
#define platform "net6.0"
[Setup]
AppName = {param:botname|NadekoBot}
AppVersion={#version}
AppPublisher=Kwoth
DefaultDirName={param:installpath|{commonpf}\NadekoBot}
DefaultGroupName=NadekoBot
UninstallDisplayIcon={app}\{#sysfolder}\nadeko_icon.ico
Compression=lzma2
SolidCompression=yes
UsePreviousLanguage=no
UsePreviousSetupType=no
UsePreviousAppDir=no
OutputDir=nadeko-installers/{#version}/
OutputBaseFilename=nadeko-setup-{#version}
AppReadmeFile=https://nadeko.bot/commands
ArchitecturesInstallIn64BitMode=x64
DisableWelcomePage=yes
DisableDirPage=yes
DisableFinishedPage=yes
DisableReadyMemo=yes
DisableProgramGroupPage=yes
WizardStyle=modern
UpdateUninstallLogAppName=no
CreateUninstallRegKey=no
Uninstallable=no
[Files]
;install
Source: "src\NadekoBot\bin\Release\{#platform}\{#target}\publish\*"; DestDir: "{app}\{#sysfolder}"; Permissions: users-full; Flags: recursesubdirs onlyifdoesntexist ignoreversion createallsubdirs; Excludes: "*.pdb, *.db"
;reinstall - i want to copy all files, but i don't want to overwrite any data files because users will lose their customization if they don't have a backup,
; and i don't want them to have to backup and then copy-merge into data folder themselves, or lose their currency images due to overwrite.
Source: "src\NadekoBot\bin\Release\{#platform}\{#target}\publish\*"; DestDir: "{app}\{#sysfolder}"; Permissions: users-full; Flags: recursesubdirs ignoreversion onlyifdestfileexists createallsubdirs; Excludes: "*.pdb, *.db, data\*, credentials.json, creds.yml";
Source: "src\NadekoBot\bin\Release\{#platform}\{#target}\publish\data\*"; DestDir: "{app}\{#sysfolder}\data"; Permissions: users-full; Flags: recursesubdirs onlyifdoesntexist createallsubdirs;
; overwrite strings and aliases
Source: "src\NadekoBot\bin\Release\{#platform}\{#target}\publish\data\aliases.yml"; DestDir: "{app}\{#sysfolder}\data\"; Permissions: users-full; Flags: recursesubdirs ignoreversion onlyifdestfileexists createallsubdirs;
Source: "src\NadekoBot\bin\Release\{#platform}\{#target}\publish\data\strings\*"; DestDir: "{app}\{#sysfolder}\data\strings"; Permissions: users-full; Flags: recursesubdirs ignoreversion onlyifdestfileexists createallsubdirs;
[Dirs]
Name:"{app}\{#sysfolder}\data"; Permissions: everyone-modify
Name:"{app}\{#sysfolder}\config"; Permissions: everyone-modify
Name:"{app}\{#sysfolder}"; Permissions: everyone-modify
; [Run]
; Filename: "http://nadekobot.readthedocs.io/en/latest/jsons-explained/"; Flags: postinstall shellexec runasoriginaluser; Description: "Open setup guide"
; Filename: "{app}\{#sysfolder}\creds.yml"; Flags: postinstall shellexec runasoriginaluser; Description: "Open creds file"
[Icons]
; for pretty install directory
Name: "{app}\NadekoBot"; Filename: "{app}\{#sysfolder}\NadekoBot.exe"; IconFilename: "{app}\{#sysfolder}\nadeko_icon.ico"
Name: "{app}\creds"; Filename: "{app}\{#sysfolder}\creds.yml"
Name: "{app}\data"; Filename: "{app}\{#sysfolder}\data"
; desktop shortcut
Name: "{commondesktop}\{#SetupSetting("AppName")}"; Filename: "{app}\NadekoBot";
[Code]
function GetFileName(const AFileName: string): string;
begin
Result := ExpandConstant('{app}\{#sysfolder}\' + AFileName);
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if (CurStep = ssPostInstall) then
begin
FileCopy(GetFileName('creds_example.yml'), GetFileName('creds.yml'), True);
end;
end;

View File

@ -1,4 +0,0 @@
mkdocs-material>=7.1.4
mkdocs>=1.1.2
mkdocs-git-revision-date-localized-plugin>=0.9.2
mkdocs-material-extensions>=1.0.1

View File

@ -1,92 +0,0 @@
site_name: 'NadekoBot'
site_url: 'https://nadeko.bot'
repo_url: 'https://gitlab.com/kwoth/nadekobot'
site_author: 'Kwoth'
theme:
name: material
custom_dir: docs/overrides
palette:
- media: "(prefers-color-scheme: light)"
scheme: default
primary: blue
accent: light blue
toggle:
icon: material/weather-sunny
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: dark
primary: blue
accent: light blue
toggle:
icon: material/weather-night
name: Switch to light mode
features:
- navigation.instant
- navigation.expand
- navigation.top
font:
text: Source Sans Pro
code: Source Code Pro
logo: assets/favicon.png
favicon: assets/favicon.png
icon:
repo: custom/gitlab
extra:
homepage: https://nadeko.bot
extra_css:
- stylesheets/styling-overrides.css
- stylesheets/theme.css
plugins:
- git-revision-date-localized:
type: date
- search
markdown_extensions:
- attr_list
- codehilite:
guess_lang: false
- toc:
permalink: true
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.betterem:
smart_enable: all
- admonition
- meta
- footnotes
- pymdownx.details
- pymdownx.inlinehilite
- pymdownx.superfences
- pymdownx.tabbed
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
options:
custom_icons:
- docs/overrides/.icons
nav:
- Home: index.md
- Guides:
- Windows Guide: guides/windows-guide.md
- Linux Guide: guides/linux-guide.md
- OSX Guide: guides/osx-guide.md
- Docker Guide (unsupported): guides/docker-guide.md
- Commands:
- Readme: commands-readme.md
- Commands List: https://nadeko.bot/commands
- Features Explained:
- Basic Creds: creds-guide.md
- Advanced Creds: jsons-explained.md
- Permissions System: permissions-system.md
- Custom Reactions: custom-reactions.md
- Placeholders: placeholders.md
- Config: config-guide.md
- Bot Config: bce-guide.md
- Contribution Guide: contribution-guide.md
- Donate: donate.md
- License: license.md

View File

@ -1,63 +0,0 @@
function Get-Changelog($lastTag)
{
if(!$lastTag)
{
$lastTag = git describe --tags --abbrev=0
}
$tag = "$lastTag..HEAD"
$clArr = (git log $tag --oneline)
[array]::Reverse($clArr)
$changelog = $clArr | where { "$_" -notlike "*(POEditor.com)*" -and "$_" -notlike "*Merge branch*" -and "$_" -notlike "*Merge pull request*" -and "$_" -notlike "^-*" -and "$_" -notlike "*Merge remote tracking*" }
$changelog = [string]::join([Environment]::NewLine, $changelog)
$cl2 = $clArr | where { "$_" -like "*Merge pull request*" }
$changelog = "## Changes$nl$changelog"
if ($null -ne $cl2) {
$cl2 = [string]::join([Environment]::NewLine, $cl2)
$changelog = $changelog + "$nl ## Pull Requests Merged$nl$cl2"
}
return $changelog
}
function Build-Installer($versionNumber)
{
$env:NADEKOBOT_INSTALL_VERSION = $versionNumber
dotnet clean
# rm -r -fo "src\NadekoBot\bin"
dotnet publish -c Release --runtime win7-x64 /p:Version=$versionNumber src/NadekoBot
# .\rcedit-x64.exe "src\NadekoBot\bin\Release\netcoreapp2.1\win7-x64\nadekobot.exe" --set-icon "src\NadekoBot\bin\Release\netcoreapp2.1\win7-x64\nadeko_icon.ico"
& "iscc.exe" "/O+" ".\exe_builder.iss"
Write-ReleaseFile($versionNumber)
# $path = [Environment]::GetFolderPath('MyDocuments') + "\_projekti\new_installer\$versionNumber\";
# $binPath = $path + "nadeko-setup-$versionNumber.exe";
# Copy-Item -Path $path -Destination $dest -Force -ErrorAction Stop
# return $path
}
function Write-ReleaseFile($versionNumber) {
$changelog = ""
# pull the changes if they exist
# git pull
# attempt to build teh installer
# $path = Build-Installer $versionNumber
# get changelog before tagging
$changelog = Get-Changelog
# tag the release
# & (git tag, $tag)
# print out the changelog to the console
# Write-Host $changelog
$jsonReleaseFile = "[{""VersionName"": ""$versionNumber"", ""DownloadLink"": ""https://cdn.nadeko.bot/dl/bot/nadeko-setup-$versionNumber.exe"", ""Changelog"": """"}]"
$releaseJsonOutPath = [Environment]::GetFolderPath('MyDocuments') + "\_projekti\nadeko-installers\$versionNumber\"
New-Item -Path $releaseJsonOutPath -Value $jsonReleaseFile -Name "releases.json" -Force
}

View File

@ -1 +0,0 @@
[{ "VersionName":"_VERSION_", "DownloadLink":"https://cdn.nadeko.bot/dl/bot/_INSTALLER_FILE_NAME_" }]

View File

@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Protobuf Include="Protos\coordinator.proto" GrpcServices="Server" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.42.0" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="YamlDotNet" Version="11.2.1" />
</ItemGroup>
</Project>

View File

@ -1,323 +0,0 @@
#nullable enable
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace NadekoBot.Generators.Command;
[Generator]
public class CommandAttributesGenerator : IIncrementalGenerator
{
public const string ATTRIBUTE = @"// <AutoGenerated />
namespace NadekoBot.Common;
[System.AttributeUsage(System.AttributeTargets.Method)]
public class CmdAttribute : System.Attribute
{
}";
public class MethodModel
{
public string? Namespace { get; }
public IReadOnlyCollection<string> Classes { get; }
public string ReturnType { get; }
public string MethodName { get; }
public IEnumerable<string> Params { get; }
public MethodModel(string? ns, IReadOnlyCollection<string> classes, string returnType, string methodName, IEnumerable<string> @params)
{
Namespace = ns;
Classes = classes;
ReturnType = returnType;
MethodName = methodName;
Params = @params;
}
}
public class FileModel
{
public string? Namespace { get; }
public IReadOnlyCollection<string> ClassHierarchy { get; }
public IReadOnlyCollection<MethodModel> Methods { get; }
public FileModel(string? ns, IReadOnlyCollection<string> classHierarchy, IReadOnlyCollection<MethodModel> methods)
{
Namespace = ns;
ClassHierarchy = classHierarchy;
Methods = methods;
}
}
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// #if DEBUG
// SpinWait.SpinUntil(() => Debugger.IsAttached);
// #endif
context.RegisterPostInitializationOutput(static ctx => ctx.AddSource(
"CmdAttribute.g.cs",
SourceText.From(ATTRIBUTE, Encoding.UTF8)));
var methods = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 },
static (ctx, cancel) => Transform(ctx, cancel))
.Where(static m => m is not null)
.Where(static m => m?.ChildTokens().Any(static x => x.IsKind(SyntaxKind.PublicKeyword)) ?? false);
var compilationMethods = context.CompilationProvider.Combine(methods.Collect());
context.RegisterSourceOutput(compilationMethods,
static (ctx, tuple) => RegisterAction(in ctx, tuple.Left, in tuple.Right));
}
private static void RegisterAction(in SourceProductionContext ctx,
Compilation comp,
in ImmutableArray<MethodDeclarationSyntax?> methods)
{
if (methods is { IsDefaultOrEmpty: true })
return;
var models = GetModels(comp, methods, ctx.CancellationToken);
foreach (var model in models)
{
var name = $"{model.Namespace}.{string.Join(".", model.ClassHierarchy)}.g.cs";
try
{
Debug.WriteLine($"Writing {name}");
var source = GetSourceText(model);
ctx.AddSource(name, SourceText.From(source, Encoding.UTF8));
}
catch (Exception ex)
{
Debug.WriteLine($"Error writing source file {name}\n" + ex);
}
}
}
private static string GetSourceText(FileModel model)
{
using var sw = new StringWriter();
using var tw = new IndentedTextWriter(sw);
tw.WriteLine("// <AutoGenerated />");
tw.WriteLine("#pragma warning disable CS1066");
if (model.Namespace is not null)
{
tw.WriteLine($"namespace {model.Namespace};");
tw.WriteLine();
}
foreach (var className in model.ClassHierarchy)
{
tw.WriteLine($"public partial class {className}");
tw.WriteLine("{");
tw.Indent ++;
}
foreach (var method in model.Methods)
{
tw.WriteLine("[NadekoCommand]");
tw.WriteLine("[NadekoDescription]");
tw.WriteLine("[Aliases]");
tw.WriteLine($"public partial {method.ReturnType} {method.MethodName}({string.Join(", ", method.Params)});");
}
foreach (var _ in model.ClassHierarchy)
{
tw.Indent --;
tw.WriteLine("}");
}
tw.Flush();
return sw.ToString();
}
private static IReadOnlyCollection<FileModel> GetModels(Compilation compilation,
in ImmutableArray<MethodDeclarationSyntax?> inputMethods,
CancellationToken cancel)
{
var models = new List<FileModel>();
var methods = inputMethods
.Where(static x => x is not null)
.Distinct();
var methodModels = methods
.Select(x => MethodDeclarationToMethodModel(compilation, x!));
var groups = methodModels
.GroupBy(static x => $"{x.Namespace}.{string.Join(".", x.Classes)}");
foreach (var group in groups)
{
if (cancel.IsCancellationRequested)
return new Collection<FileModel>();
if (group is null)
continue;
var elems = group.ToList();
if (elems.Count is 0)
continue;
var model = new FileModel(
methods: elems,
ns: elems[0].Namespace,
classHierarchy: elems[0].Classes
);
models.Add(model);
}
return models;
}
private static MethodModel MethodDeclarationToMethodModel(Compilation comp, MethodDeclarationSyntax decl)
{
// SpinWait.SpinUntil(static () => Debugger.IsAttached);
var semanticModel = comp.GetSemanticModel(decl.SyntaxTree);
var methodModel = new MethodModel(
@params: decl.ParameterList.Parameters
.Where(p => p.Type is not null)
.Select(p =>
{
var prefix = p.Modifiers.Any(static x => x.IsKind(SyntaxKind.ParamsKeyword))
? "params "
: string.Empty;
var type = semanticModel
.GetTypeInfo(p.Type!)
.Type
?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var name = p.Identifier.Text;
var suffix = string.Empty;
if (p.Default is not null)
{
if (p.Default.Value is LiteralExpressionSyntax)
{
suffix = " = " + p.Default.Value;
}
else if (p.Default.Value is MemberAccessExpressionSyntax maes)
{
var maesSemModel = comp.GetSemanticModel(maes.SyntaxTree);
var sym = maesSemModel.GetSymbolInfo(maes.Name);
if (sym.Symbol is null)
{
suffix = " = " + p.Default.Value;
}
else
{
suffix = " = " + sym.Symbol.ToDisplayString();
}
}
}
return $"{prefix}{type} {name}{suffix}";
})
.ToList(),
methodName: decl.Identifier.Text,
returnType: decl.ReturnType.ToString(),
ns: GetNamespace(decl),
classes: GetClasses(decl)
);
return methodModel;
}
//https://github.com/andrewlock/NetEscapades.EnumGenerators/blob/main/src/NetEscapades.EnumGenerators/EnumGenerator.cs
static string? GetNamespace(MethodDeclarationSyntax declarationSyntax)
{
// determine the namespace the class is declared in, if any
string? nameSpace = null;
var parentOfInterest = declarationSyntax.Parent;
while (parentOfInterest is not null)
{
parentOfInterest = parentOfInterest.Parent;
if (parentOfInterest is BaseNamespaceDeclarationSyntax ns)
{
nameSpace = ns.Name.ToString();
while (true)
{
if (ns.Parent is not NamespaceDeclarationSyntax parent)
{
break;
}
ns = parent;
nameSpace = $"{ns.Name}.{nameSpace}";
}
return nameSpace;
}
}
return nameSpace;
}
static IReadOnlyCollection<string> GetClasses(MethodDeclarationSyntax declarationSyntax)
{
// determine the namespace the class is declared in, if any
var classes = new LinkedList<string>();
var parentOfInterest = declarationSyntax.Parent;
while (parentOfInterest is not null)
{
if (parentOfInterest is ClassDeclarationSyntax cds)
{
classes.AddFirst(cds.Identifier.ToString());
}
parentOfInterest = parentOfInterest.Parent;
}
Debug.WriteLine($"Method {declarationSyntax.Identifier.Text} has {classes.Count} classes");
return classes;
}
private static MethodDeclarationSyntax? Transform(GeneratorSyntaxContext ctx, CancellationToken cancel)
{
var methodDecl = ctx.Node as MethodDeclarationSyntax;
if (methodDecl is null)
return default;
foreach (var attListSyntax in methodDecl.AttributeLists)
{
foreach (var attSyntax in attListSyntax.Attributes)
{
if (cancel.IsCancellationRequested)
return default;
var symbol = ctx.SemanticModel.GetSymbolInfo(attSyntax).Symbol;
if (symbol is not IMethodSymbol attSymbol)
continue;
if (attSymbol.ContainingType.ToDisplayString() == "NadekoBot.Common.CmdAttribute")
return methodDecl;
}
}
return default;
}
}

View File

@ -1,76 +0,0 @@
using System.Linq;
using System.Threading.Tasks;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NUnit.Framework;
namespace NadekoBot.Tests
{
public class GroupGreetTests
{
private GreetGrouper<int> _grouper;
[SetUp]
public void Setup()
=> _grouper = new GreetGrouper<int>();
[Test]
public void CreateTest()
{
var created = _grouper.CreateOrAdd(0, 5);
Assert.True(created);
}
[Test]
public void CreateClearTest()
{
_grouper.CreateOrAdd(0, 5);
_grouper.ClearGroup(0, 5, out var items);
Assert.AreEqual(0, items.Count());
}
[Test]
public void NotCreatedTest()
{
_grouper.CreateOrAdd(0, 5);
var created = _grouper.CreateOrAdd(0, 4);
Assert.False(created);
}
[Test]
public void ClearAddedTest()
{
_grouper.CreateOrAdd(0, 5);
_grouper.CreateOrAdd(0, 4);
_grouper.ClearGroup(0, 5, out var items);
var list = items.ToList();
Assert.AreEqual(1, list.Count, $"Count was {list.Count}");
Assert.AreEqual(4, list[0]);
}
[Test]
public async Task ClearManyTest()
{
_grouper.CreateOrAdd(0, 5);
// add 15 items
await Enumerable.Range(10, 15)
.Select(x => Task.Run(() => _grouper.CreateOrAdd(0, x))).WhenAll();
// get 5 at most
_grouper.ClearGroup(0, 5, out var items);
var list = items.ToList();
Assert.AreEqual(5, list.Count, $"Count was {list.Count}");
// try to get 15, but there should be 10 left
_grouper.ClearGroup(0, 15, out items);
list = items.ToList();
Assert.AreEqual(10, list.Count, $"Count was {list.Count}");
}
}
}

View File

@ -1,41 +0,0 @@
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace NadekoBot.VotesApi
{
public class AuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public const string SchemeName = "AUTHORIZATION_SCHEME";
public const string DiscordsClaim = "DISCORDS_CLAIM";
public const string TopggClaim = "TOPGG_CLAIM";
private readonly IConfiguration _conf;
public AuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IConfiguration conf)
: base(options, logger, encoder, clock)
=> _conf = conf;
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new List<Claim>();
if (_conf[ConfKeys.DISCORDS_KEY].Trim() == Request.Headers["Authorization"].ToString().Trim())
claims.Add(new(DiscordsClaim, "true"));
if (_conf[ConfKeys.TOPGG_KEY] == Request.Headers["Authorization"].ToString().Trim())
claims.Add(new Claim(TopggClaim, "true"));
return Task.FromResult(AuthenticateResult.Success(new(new(new ClaimsIdentity(claims)), SchemeName)));
}
}
}

View File

@ -1,33 +0,0 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NadekoBot.VotesApi.Services;
namespace NadekoBot.VotesApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class DiscordsController : ControllerBase
{
private readonly ILogger<DiscordsController> _logger;
private readonly IVotesCache _cache;
public DiscordsController(ILogger<DiscordsController> logger, IVotesCache cache)
{
_logger = logger;
_cache = cache;
}
[HttpGet("new")]
[Authorize(Policy = Policies.DiscordsAuth)]
public async Task<IEnumerable<Vote>> New()
{
var votes = await _cache.GetNewDiscordsVotesAsync();
if(votes.Count > 0)
_logger.LogInformation("Sending {NewDiscordsVotes} new discords votes", votes.Count);
return votes;
}
}
}

View File

@ -1,34 +0,0 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NadekoBot.VotesApi.Services;
namespace NadekoBot.VotesApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class TopGgController : ControllerBase
{
private readonly ILogger<TopGgController> _logger;
private readonly IVotesCache _cache;
public TopGgController(ILogger<TopGgController> logger, IVotesCache cache)
{
_logger = logger;
_cache = cache;
}
[HttpGet("new")]
[Authorize(Policy = Policies.TopggAuth)]
public async Task<IEnumerable<Vote>> New()
{
var votes = await _cache.GetNewTopGgVotesAsync();
if(votes.Count > 0)
_logger.LogInformation("Sending {NewTopggVotes} new topgg votes", votes.Count);
return votes;
}
}
}

View File

@ -1,48 +0,0 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NadekoBot.VotesApi.Services;
namespace NadekoBot.VotesApi.Controllers
{
[ApiController]
public class WebhookController : ControllerBase
{
private readonly ILogger<WebhookController> _logger;
private readonly IVotesCache _votesCache;
public WebhookController(ILogger<WebhookController> logger, IVotesCache votesCache)
{
_logger = logger;
_votesCache = votesCache;
}
[HttpPost("/discordswebhook")]
[Authorize(Policy = Policies.DiscordsAuth)]
public async Task<IActionResult> DiscordsWebhook([FromBody]DiscordsVoteWebhookModel data)
{
_logger.LogInformation("User {UserId} has voted for Bot {BotId} on {Platform}",
data.User,
data.Bot,
"discords.com");
await _votesCache.AddNewDiscordsVote(data.User);
return Ok();
}
[HttpPost("/topggwebhook")]
[Authorize(Policy = Policies.TopggAuth)]
public async Task<IActionResult> TopggWebhook([FromBody] TopggVoteWebhookModel data)
{
_logger.LogInformation("User {UserId} has voted for Bot {BotId} on {Platform}",
data.User,
data.Bot,
"top.gg");
await _votesCache.AddNewTopggVote(data.User);
return Ok();
}
}
}

View File

@ -1,20 +0,0 @@
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["src/NadekoBot.VotesApi/NadekoBot.VotesApi.csproj", "NadekoBot.VotesApi/"]
RUN dotnet restore "src/NadekoBot.VotesApi/NadekoBot.VotesApi.csproj"
COPY . .
WORKDIR "/src/NadekoBot.VotesApi"
RUN dotnet build "NadekoBot.VotesApi.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "NadekoBot.VotesApi.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "NadekoBot.VotesApi.dll"]

View File

@ -1,9 +0,0 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using NadekoBot.VotesApi;
CreateHostBuilder(args).Build().Run();
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

View File

@ -1,100 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using MorseCode.ITask;
namespace NadekoBot.VotesApi.Services
{
public class FileVotesCache : IVotesCache
{
// private const string STATS_FILE = "store/stats.json";
private const string TOPGG_FILE = "store/topgg.json";
private const string DISCORDS_FILE = "store/discords.json";
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
public FileVotesCache()
{
if (!Directory.Exists("store"))
Directory.CreateDirectory("store");
if(!File.Exists(TOPGG_FILE))
File.WriteAllText(TOPGG_FILE, "[]");
if(!File.Exists(DISCORDS_FILE))
File.WriteAllText(DISCORDS_FILE, "[]");
}
public ITask AddNewTopggVote(string userId)
=> AddNewVote(TOPGG_FILE, userId);
public ITask AddNewDiscordsVote(string userId)
=> AddNewVote(DISCORDS_FILE, userId);
private async ITask AddNewVote(string file, string userId)
{
await _locker.WaitAsync();
try
{
var votes = await GetVotesAsync(file);
votes.Add(userId);
await File.WriteAllTextAsync(file , JsonSerializer.Serialize(votes));
}
finally
{
_locker.Release();
}
}
public async ITask<IList<Vote>> GetNewTopGgVotesAsync()
{
var votes = await EvictTopggVotes();
return votes;
}
public async ITask<IList<Vote>> GetNewDiscordsVotesAsync()
{
var votes = await EvictDiscordsVotes();
return votes;
}
private ITask<List<Vote>> EvictTopggVotes()
=> EvictVotes(TOPGG_FILE);
private ITask<List<Vote>> EvictDiscordsVotes()
=> EvictVotes(DISCORDS_FILE);
private async ITask<List<Vote>> EvictVotes(string file)
{
await _locker.WaitAsync();
try
{
var ids = await GetVotesAsync(file);
await File.WriteAllTextAsync(file, "[]");
return ids?
.Select(x => (Ok: ulong.TryParse(x, out var r), Id: r))
.Where(x => x.Ok)
.Select(x => new Vote
{
UserId = x.Id
})
.ToList();
}
finally
{
_locker.Release();
}
}
private async ITask<IList<string>> GetVotesAsync(string file)
{
await using var fs = File.Open(file, FileMode.Open);
var votes = await JsonSerializer.DeserializeAsync<List<string>>(fs);
return votes;
}
}
}

View File

@ -1,13 +0,0 @@
using System.Collections.Generic;
using MorseCode.ITask;
namespace NadekoBot.VotesApi.Services
{
public interface IVotesCache
{
ITask<IList<Vote>> GetNewTopGgVotesAsync();
ITask<IList<Vote>> GetNewDiscordsVotesAsync();
ITask AddNewTopggVote(string userId);
ITask AddNewDiscordsVote(string userId);
}
}

View File

@ -1,359 +0,0 @@
root = true
# Remove the line below if you want to inherit .editorconfig settings from higher directories
[obj/**]
generated_code = true
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
# New line preferences
end_of_line = crlf
insert_final_newline = false
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
# this. and Me. preferences
dotnet_style_qualification_for_event = false
dotnet_style_qualification_for_field = false
dotnet_style_qualification_for_method = false
dotnet_style_qualification_for_property = false
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_other_operators = never_if_unnecessary
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning
# Modifier preferences
dotnet_style_require_accessibility_modifiers = always:error
# Expression-level preferences
dotnet_style_coalesce_expression = true
dotnet_style_collection_initializer = true
dotnet_style_explicit_tuple_names = true
dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true
dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
dotnet_style_prefer_conditional_expression_over_return = false:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
dotnet_style_prefer_simplified_boolean_expressions = true
dotnet_style_prefer_simplified_interpolation = true
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:warning
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = true
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:suggestion
csharp_style_expression_bodied_constructors = when_on_single_line:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_lambdas = true:suggestion
csharp_style_expression_bodied_local_functions = true:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_operators = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:error
csharp_style_pattern_matching_over_is_with_cast_check = true:error
csharp_style_prefer_not_pattern = true:error
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_switch_expression = true
# Null-checking preferences
csharp_style_conditional_delegate_call = true:error
# Modifier preferences
csharp_prefer_static_local_function = true
csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async
# Code-block preferences
csharp_prefer_braces = when_multiline:warning
csharp_prefer_simple_using_statement = true
# Expression-level preferences
csharp_prefer_simple_default_expression = true
csharp_style_deconstructed_variable_declaration = true
csharp_style_implicit_object_creation_when_type_is_apparent = true:error
csharp_style_inlined_variable_declaration = true:warning
csharp_style_pattern_local_over_anonymous_function = true
csharp_style_prefer_index_operator = true
csharp_style_prefer_range_operator = true
csharp_style_throw_expression = true:error
csharp_style_unused_value_assignment_preference = discard_variable:warning
csharp_style_unused_value_expression_statement_preference = discard_variable
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:error
# Enforce file-scoped namespaces
csharp_style_namespace_declarations = file_scoped:error
# New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
csharp_style_allow_embedded_statements_on_same_line_experimental = false
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false
#### Naming styles ####
# Naming rules
dotnet_naming_rule.private_readonly_field.symbols = private_readonly_field
dotnet_naming_rule.private_readonly_field.style = begins_with_underscore
dotnet_naming_rule.private_readonly_field.severity = warning
dotnet_naming_rule.private_field.symbols = private_field
dotnet_naming_rule.private_field.style = camel_case
dotnet_naming_rule.private_field.severity = warning
dotnet_naming_rule.const_fields.symbols = const_fields
dotnet_naming_rule.const_fields.style = all_upper
dotnet_naming_rule.const_fields.severity = warning
# dotnet_naming_rule.class_should_be_pascal_case.severity = error
# dotnet_naming_rule.class_should_be_pascal_case.symbols = class
# dotnet_naming_rule.class_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.struct_should_be_pascal_case.severity = error
dotnet_naming_rule.struct_should_be_pascal_case.symbols = struct
dotnet_naming_rule.struct_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.interface_should_be_begins_with_i.severity = error
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
# dotnet_naming_rule.types_should_be_pascal_case.severity = error
# dotnet_naming_rule.types_should_be_pascal_case.symbols = types
# dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
# dotnet_naming_rule.enum_should_be_pascal_case.severity = error
# dotnet_naming_rule.enum_should_be_pascal_case.symbols = enum
# dotnet_naming_rule.enum_should_be_pascal_case.style = pascal_case
# dotnet_naming_rule.property_should_be_pascal_case.severity = error
# dotnet_naming_rule.property_should_be_pascal_case.symbols = property
# dotnet_naming_rule.property_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.method_should_be_pascal_case.severity = error
dotnet_naming_rule.method_should_be_pascal_case.symbols = method
dotnet_naming_rule.method_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.async_method_should_be_ends_with_async.severity = error
dotnet_naming_rule.async_method_should_be_ends_with_async.symbols = async_method
dotnet_naming_rule.async_method_should_be_ends_with_async.style = ends_with_async
# dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = error
# dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
# dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.local_variable_should_be_camel_case.severity = error
dotnet_naming_rule.local_variable_should_be_camel_case.symbols = local_variable
dotnet_naming_rule.local_variable_should_be_camel_case.style = camel_case
# Symbol specifications
dotnet_naming_symbols.const_fields.required_modifiers = const
dotnet_naming_symbols.const_fields.applicable_kinds = field
dotnet_naming_symbols.class.applicable_kinds = class
dotnet_naming_symbols.class.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.class.required_modifiers =
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.struct.applicable_kinds = struct
dotnet_naming_symbols.struct.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.struct.required_modifiers =
dotnet_naming_symbols.enum.applicable_kinds = enum
dotnet_naming_symbols.enum.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.enum.required_modifiers =
dotnet_naming_symbols.method.applicable_kinds = method
dotnet_naming_symbols.method.applicable_accessibilities = public
dotnet_naming_symbols.method.required_modifiers =
dotnet_naming_symbols.property.applicable_kinds = property
dotnet_naming_symbols.property.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.property.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
dotnet_naming_symbols.private_readonly_field.applicable_kinds = field
dotnet_naming_symbols.private_readonly_field.applicable_accessibilities = private, protected
dotnet_naming_symbols.private_readonly_field.required_modifiers = readonly
dotnet_naming_symbols.private_field.applicable_kinds = field
dotnet_naming_symbols.private_field.applicable_accessibilities = private, protected
dotnet_naming_symbols.private_field.required_modifiers =
dotnet_naming_symbols.async_method.applicable_kinds = method, local_function
dotnet_naming_symbols.async_method.applicable_accessibilities = *
dotnet_naming_symbols.async_method.required_modifiers = async
dotnet_naming_symbols.local_variable.applicable_kinds = parameter, local
dotnet_naming_symbols.local_variable.applicable_accessibilities = local
dotnet_naming_symbols.local_variable.required_modifiers =
# Naming styles
dotnet_naming_style.all_upper.capitalization = all_upper
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.begins_with_underscore.required_prefix = _
dotnet_naming_style.begins_with_underscore.required_suffix =
dotnet_naming_style.begins_with_underscore.word_separator =
dotnet_naming_style.begins_with_underscore.capitalization = camel_case
dotnet_naming_style.ends_with_async.required_prefix =
# dotnet_naming_style.ends_with_async.required_suffix = Async
dotnet_naming_style.ends_with_async.word_separator =
dotnet_naming_style.ends_with_async.capitalization = pascal_case
dotnet_naming_style.camel_case.required_prefix =
dotnet_naming_style.camel_case.required_suffix =
dotnet_naming_style.camel_case.word_separator =
dotnet_naming_style.camel_case.capitalization = camel_case
# CA1822: Mark members as static
dotnet_diagnostic.ca1822.severity = suggestion
# IDE0004: Cast is redundant
dotnet_diagnostic.ide0004.severity = warning
# IDE0058: Expression value is never used
dotnet_diagnostic.ide0058.severity = none
# # IDE0011: Add braces to 'if'/'else' statement
# dotnet_diagnostic.ide0011.severity = none
resharper_wrap_after_invocation_lpar = false
resharper_wrap_before_invocation_rpar = false
# ReSharper properties
resharper_align_multiline_calls_chain = true
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_after_invocation_lpar = false
resharper_csharp_wrap_before_binary_opsign = true
resharper_csharp_wrap_before_invocation_rpar = false
resharper_csharp_wrap_parameters_style = chop_if_long
resharper_force_chop_compound_if_expression = false
resharper_keep_existing_linebreaks = true
resharper_keep_user_linebreaks = true
resharper_max_formal_parameters_on_line = 3
resharper_place_simple_embedded_statement_on_same_line = false
resharper_wrap_chained_binary_expressions = chop_if_long
resharper_wrap_chained_binary_patterns = chop_if_long
resharper_wrap_chained_method_calls = chop_if_long
resharper_wrap_object_and_collection_initializer_style = chop_always
resharper_csharp_wrap_before_first_type_parameter_constraint = true
resharper_csharp_place_type_constraints_on_same_line = false
resharper_csharp_wrap_before_extends_colon = true
resharper_csharp_place_constructor_initializer_on_same_line = false
resharper_force_attribute_style = separate
resharper_csharp_braces_for_ifelse = required_for_multiline_statement
resharper_csharp_braces_for_foreach = required_for_multiline
resharper_csharp_braces_for_while = required_for_multiline
resharper_csharp_braces_for_for = required_for_multiline
resharper_arrange_redundant_parentheses_highlighting = hint
# IDE0011: Add braces
dotnet_diagnostic.IDE0011.severity = warning

View File

@ -1,383 +0,0 @@
#nullable disable
using Microsoft.Extensions.DependencyInjection;
using NadekoBot.Common.Configs;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Db;
using NadekoBot.Modules.Administration;
using NadekoBot.Services.Database.Models;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using RunMode = Discord.Commands.RunMode;
namespace NadekoBot;
public sealed class Bot
{
public event Func<GuildConfig, Task> JoinedGuild = delegate { return Task.CompletedTask; };
public DiscordSocketClient Client { get; }
public ImmutableArray<GuildConfig> AllGuildConfigs { get; private set; }
private IServiceProvider Services { get; set; }
public string Mention { get; private set; }
public bool IsReady { get; private set; }
public int ShardId { get; set; }
private readonly IBotCredentials _creds;
private readonly CommandService _commandService;
private readonly DbService _db;
private readonly IBotCredsProvider _credsProvider;
// private readonly InteractionService _interactionService;
public Bot(int shardId, int? totalShards)
{
if (shardId < 0)
throw new ArgumentOutOfRangeException(nameof(shardId));
ShardId = shardId;
_credsProvider = new BotCredsProvider(totalShards);
_creds = _credsProvider.GetCreds();
_db = new(_creds);
if (shardId == 0)
_db.Setup();
var messageCacheSize =
#if GLOBAL_NADEKO
0;
#else
50;
#endif
if(!_creds.UsePrivilegedIntents)
Log.Warning("You are not using privileged intents. Some features will not work properly");
Client = new(new()
{
MessageCacheSize = messageCacheSize,
LogLevel = LogSeverity.Warning,
ConnectionTimeout = int.MaxValue,
TotalShards = _creds.TotalShards,
ShardId = shardId,
AlwaysDownloadUsers = false,
AlwaysResolveStickers = false,
AlwaysDownloadDefaultStickers = false,
GatewayIntents = _creds.UsePrivilegedIntents
? GatewayIntents.All
: GatewayIntents.AllUnprivileged,
LogGatewayIntentWarnings = false,
});
_commandService = new(new()
{
CaseSensitiveCommands = false,
DefaultRunMode = RunMode.Sync
});
// _interactionService = new(Client.Rest);
Client.Log += Client_Log;
}
public List<ulong> GetCurrentGuildIds()
=> Client.Guilds.Select(x => x.Id).ToList();
private void AddServices()
{
var startingGuildIdList = GetCurrentGuildIds();
var sw = Stopwatch.StartNew();
var bot = Client.CurrentUser;
using (var uow = _db.GetDbContext())
{
uow.EnsureUserCreated(bot.Id, bot.Username, bot.Discriminator, bot.AvatarId);
AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(startingGuildIdList).ToImmutableArray();
}
var svcs = new ServiceCollection().AddTransient(_ => _credsProvider.GetCreds()) // bot creds
.AddSingleton(_credsProvider)
.AddSingleton(_db) // database
.AddRedis(_creds.RedisOptions) // redis
.AddSingleton(Client) // discord socket client
.AddSingleton(_commandService)
// .AddSingleton(_interactionService)
.AddSingleton(this)
.AddSingleton<ISeria, JsonSeria>()
.AddSingleton<IPubSub, RedisPubSub>()
.AddSingleton<IConfigSeria, YamlSeria>()
.AddBotStringsServices(_creds.TotalShards)
.AddConfigServices()
.AddConfigMigrators()
.AddMemoryCache()
// music
.AddMusic();
// admin
#if GLOBAL_NADEKO
svcs.AddSingleton<ILogCommandService, DummyLogCommandService>();
#else
svcs.AddSingleton<ILogCommandService, LogCommandService>();
#endif
svcs.AddHttpClient();
svcs.AddHttpClient("memelist")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AllowAutoRedirect = false
});
if (Environment.GetEnvironmentVariable("NADEKOBOT_IS_COORDINATED") != "1")
svcs.AddSingleton<ICoordinator, SingleProcessCoordinator>();
else
{
svcs.AddSingleton<RemoteGrpcCoordinator>()
.AddSingleton<ICoordinator>(x => x.GetRequiredService<RemoteGrpcCoordinator>())
.AddSingleton<IReadyExecutor>(x => x.GetRequiredService<RemoteGrpcCoordinator>());
}
svcs.AddSingleton<RedisLocalDataCache>()
.AddSingleton<ILocalDataCache>(x => x.GetRequiredService<RedisLocalDataCache>())
.AddSingleton<RedisImagesCache>()
.AddSingleton<IImageCache>(x => x.GetRequiredService<RedisImagesCache>())
.AddSingleton<IReadyExecutor>(x => x.GetRequiredService<RedisImagesCache>())
.AddSingleton<IDataCache, RedisCache>();
svcs.Scan(scan => scan.FromAssemblyOf<IReadyExecutor>()
.AddClasses(classes => classes.AssignableToAny(
// services
typeof(INService),
// behaviours
typeof(IEarlyBehavior),
typeof(ILateBlocker),
typeof(IInputTransformer),
typeof(ILateExecutor))
#if GLOBAL_NADEKO
.WithoutAttribute<NoPublicBotAttribute>()
#endif
)
.AsSelfWithInterfaces()
.WithSingletonLifetime());
//initialize Services
Services = svcs.BuildServiceProvider();
var exec = Services.GetRequiredService<IBehaviourExecutor>();
exec.Initialize();
if (Client.ShardId == 0)
ApplyConfigMigrations();
_ = LoadTypeReaders(typeof(Bot).Assembly);
sw.Stop();
Log.Information( "All services loaded in {ServiceLoadTime:F2}s", sw.Elapsed.TotalSeconds);
}
private void ApplyConfigMigrations()
{
// execute all migrators
var migrators = Services.GetServices<IConfigMigrator>();
foreach (var migrator in migrators)
migrator.EnsureMigrated();
}
private IEnumerable<object> LoadTypeReaders(Assembly assembly)
{
Type[] allTypes;
try
{
allTypes = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
Log.Warning(ex.LoaderExceptions[0], "Error getting types");
return Enumerable.Empty<object>();
}
var filteredTypes = allTypes.Where(x => x.IsSubclassOf(typeof(TypeReader))
&& x.BaseType?.GetGenericArguments().Length > 0
&& !x.IsAbstract);
var toReturn = new List<object>();
foreach (var ft in filteredTypes)
{
var x = (TypeReader)ActivatorUtilities.CreateInstance(Services, ft);
var baseType = ft.BaseType;
if (baseType is null)
continue;
var typeArgs = baseType.GetGenericArguments();
_commandService.AddTypeReader(typeArgs[0], x);
toReturn.Add(x);
}
return toReturn;
}
private async Task LoginAsync(string token)
{
var clientReady = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
async Task SetClientReady()
{
clientReady.TrySetResult(true);
try
{
foreach (var chan in await Client.GetDMChannelsAsync())
await chan.CloseAsync();
}
catch
{
// ignored
}
}
//connect
Log.Information("Shard {ShardId} logging in ...", Client.ShardId);
try
{
Client.Ready += SetClientReady;
await Client.LoginAsync(TokenType.Bot, token);
await Client.StartAsync();
}
catch (HttpException ex)
{
LoginErrorHandler.Handle(ex);
Helpers.ReadErrorAndExit(3);
}
catch (Exception ex)
{
LoginErrorHandler.Handle(ex);
Helpers.ReadErrorAndExit(4);
}
await clientReady.Task.ConfigureAwait(false);
Client.Ready -= SetClientReady;
Client.JoinedGuild += Client_JoinedGuild;
Client.LeftGuild += Client_LeftGuild;
Log.Information("Shard {ShardId} logged in", Client.ShardId);
}
private Task Client_LeftGuild(SocketGuild arg)
{
Log.Information("Left server: {GuildName} [{GuildId}]", arg?.Name, arg?.Id);
return Task.CompletedTask;
}
private Task Client_JoinedGuild(SocketGuild arg)
{
Log.Information("Joined server: {GuildName} [{GuildId}]", arg.Name, arg.Id);
_ = Task.Run(async () =>
{
GuildConfig gc;
await using (var uow = _db.GetDbContext())
{
gc = uow.GuildConfigsForId(arg.Id, null);
}
await JoinedGuild.Invoke(gc);
});
return Task.CompletedTask;
}
public async Task RunAsync()
{
var sw = Stopwatch.StartNew();
await LoginAsync(_creds.Token);
Mention = Client.CurrentUser.Mention;
Log.Information("Shard {ShardId} loading services...", Client.ShardId);
try
{
AddServices();
}
catch (Exception ex)
{
Log.Error(ex, "Error adding services");
Helpers.ReadErrorAndExit(9);
}
sw.Stop();
Log.Information("Shard {ShardId} connected in {Elapsed:F2}s", Client.ShardId, sw.Elapsed.TotalSeconds);
var commandHandler = Services.GetRequiredService<CommandHandler>();
// start handling messages received in commandhandler
await commandHandler.StartHandling();
await _commandService.AddModulesAsync(typeof(Bot).Assembly, Services);
// await _interactionService.AddModulesAsync(typeof(Bot).Assembly, Services);
IsReady = true;
_ = Task.Run(ExecuteReadySubscriptions);
Log.Information("Shard {ShardId} ready", Client.ShardId);
}
private Task ExecuteReadySubscriptions()
{
var readyExecutors = Services.GetServices<IReadyExecutor>();
var tasks = readyExecutors.Select(async toExec =>
{
try
{
await toExec.OnReadyAsync();
}
catch (Exception ex)
{
Log.Error(ex,
"Failed running OnReadyAsync method on {Type} type: {Message}",
toExec.GetType().Name,
ex.Message);
}
});
return tasks.WhenAll();
}
private Task Client_Log(LogMessage arg)
{
if (arg.Message?.Contains("unknown dispatch", StringComparison.InvariantCultureIgnoreCase) ?? false)
return Task.CompletedTask;
if (arg.Exception is { InnerException: WebSocketClosedException { CloseCode: 4014 } })
{
Log.Error(@"
Login failed.
*** Please enable privileged intents ***
Certain Nadeko features require Discord's privileged gateway intents.
These include greeting and goodbye messages, as well as creating the Owner message channels for DM forwarding.
How to enable privileged intents:
1. Head over to the Discord Developer Portal https://discord.com/developers/applications/
2. Select your Application.
3. Click on `Bot` in the left side navigation panel, and scroll down to the intents section.
4. Enable both intents.
5. Restart your bot.
Read this only if your bot is in 100 or more servers:
You'll need to apply to use the intents with Discord, but for small selfhosts, all that is required is enabling the intents in the developer portal.
Yes, this is a new thing from Discord, as of October 2020. No, there's nothing we can do about it. Yes, we're aware it worked before.
While waiting for your bot to be accepted, you can change the 'usePrivilegedIntents' inside your creds.yml to 'false', although this will break many of the nadeko's features");
}
else if (arg.Exception is not null)
Log.Warning(arg.Exception, "{ErrorSource} | {ErrorMessage}", arg.Source, arg.Message);
else
Log.Warning("{ErrorSource} | {ErrorMessage}", arg.Source, arg.Message);
return Task.CompletedTask;
}
public async Task RunAndBlockAsync()
{
await RunAsync();
await Task.Delay(-1);
}
}

View File

@ -1,10 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public enum AddRemove
{
Add = int.MinValue,
Remove = int.MinValue + 1,
Rem = int.MinValue + 1,
Rm = int.MinValue + 1
}

View File

@ -1,13 +0,0 @@
using System.Runtime.CompilerServices;
namespace NadekoBot.Common.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public sealed class NadekoCommandAttribute : CommandAttribute
{
public string MethodName { get; }
public NadekoCommandAttribute([CallerMemberName] string memberName = "")
: base(CommandNameLoadHelper.GetCommandNameFor(memberName))
=> MethodName = memberName.ToLowerInvariant();
}

View File

@ -1,30 +0,0 @@
using System.Runtime.CompilerServices;
namespace NadekoBot.Common.Attributes;
[AttributeUsage(AttributeTargets.Class)]
internal sealed class NadekoModuleAttribute : GroupAttribute
{
public NadekoModuleAttribute(string moduleName)
: base(moduleName)
{
}
}
[AttributeUsage(AttributeTargets.Method)]
internal sealed class NadekoDescriptionAttribute : SummaryAttribute
{
public NadekoDescriptionAttribute([CallerMemberName] string name = "")
: base(name.ToLowerInvariant())
{
}
}
[AttributeUsage(AttributeTargets.Method)]
internal sealed class NadekoUsageAttribute : RemarksAttribute
{
public NadekoUsageAttribute([CallerMemberName] string name = "")
: base(name.ToLowerInvariant())
{
}
}

View File

@ -1,10 +0,0 @@
namespace NadekoBot.Common.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public sealed class NadekoOptionsAttribute : Attribute
{
public Type OptionType { get; set; }
public NadekoOptionsAttribute(Type t)
=> OptionType = t;
}

View File

@ -1,36 +0,0 @@
using Microsoft.Extensions.DependencyInjection;
namespace NadekoBot.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.GetRequiredService<IDataCache>();
var rem = cache.TryAddRatelimit(context.User.Id, command.Name, Seconds);
if (rem is 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

@ -1,821 +0,0 @@
#nullable disable
#pragma warning disable
// License MIT
// Source: https://github.com/i3arnon/ConcurrentHashSet
using System.Diagnostics;
namespace System.Collections.Generic;
/// <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 DEFAULT_CAPACITY = 31;
private const int MAX_LOCK_NUMBER = 1024;
private static int DefaultConcurrencyLevel
=> PlatformHelper.ProcessorCount;
/// <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;
}
}
bool ICollection<T>.IsReadOnly
=> false;
/// <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;
}
}
private readonly IEqualityComparer<T> _comparer;
private readonly bool _growLockArray;
private int budget;
private volatile Tables tables;
/// <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, DEFAULT_CAPACITY, 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, DEFAULT_CAPACITY, 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 is 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, DEFAULT_CAPACITY, false, comparer)
{
if (collection is null)
throw new ArgumentNullException(nameof(collection));
if (comparer is 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();
var countPerLock = new int[locks.Length];
var buckets = new Node[capacity];
tables = new(buckets, locks, countPerLock);
_growLockArray = growLockArray;
budget = buckets.Length / locks.Length;
_comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));
}
/// <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[DEFAULT_CAPACITY], 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 localTables = tables;
var bucketNo = GetBucket(hashcode, localTables.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 localTables.Buckets[bucketNo]);
while (current is not null)
{
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
return true;
current = current.Next;
}
return false;
}
void ICollection<T>.Add(T item)
=> Add(item);
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
if (array is 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);
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 is not null)
{
yield return current.Item;
current = current.Next;
}
}
}
/// <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>
/// 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 localTables = tables;
GetBucketAndLockNo(hashcode,
out var bucketNo,
out var lockNo,
localTables.Buckets.Length,
localTables.Locks.Length);
lock (localTables.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 (localTables != tables)
continue;
Node previous = null;
for (var current = localTables.Buckets[bucketNo]; current is not null; current = current.Next)
{
Debug.Assert((previous is null && current == localTables.Buckets[bucketNo])
|| previous!.Next == current);
if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
{
if (previous is null)
Volatile.Write(ref localTables.Buckets[bucketNo], current.Next);
else
previous.Next = current.Next;
localTables.CountPerLock[lockNo]--;
return true;
}
previous = current;
}
}
return false;
}
}
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 localTables = tables;
GetBucketAndLockNo(hashcode,
out var bucketNo,
out var lockNo,
localTables.Buckets.Length,
localTables.Locks.Length);
var resizeDesired = false;
var lockTaken = false;
try
{
if (acquireLock)
Monitor.Enter(localTables.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 (localTables != tables)
continue;
// Try to find this item in the bucket
Node previous = null;
for (var current = localTables.Buckets[bucketNo]; current is not null; current = current.Next)
{
Debug.Assert((previous is null && current == localTables.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 localTables.Buckets[bucketNo], new(item, hashcode, localTables.Buckets[bucketNo]));
checked
{
localTables.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 (localTables.CountPerLock[lockNo] > budget)
resizeDesired = true;
}
finally
{
if (lockTaken)
Monitor.Exit(localTables.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(localTables);
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 localTables)
{
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 (localTables != 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 < localTables.CountPerLock.Length; i++)
approxCount += localTables.CountPerLock[i];
//
// If the bucket array is too empty, double the budget instead of resizing the table
//
if (approxCount < localTables.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 = (localTables.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, localTables.Locks.Length, ref locksAcquired);
var newLocks = localTables.Locks;
// Add more locks
if (_growLockArray && localTables.Locks.Length < MAX_LOCK_NUMBER)
{
newLocks = new object[localTables.Locks.Length * 2];
Array.Copy(localTables.Locks, 0, newLocks, 0, localTables.Locks.Length);
for (var i = localTables.Locks.Length; i < newLocks.Length; i++)
newLocks[i] = new();
}
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 < localTables.Buckets.Length; i++)
{
var current = localTables.Buckets[i];
while (current is not null)
{
var next = current.Next;
GetBucketAndLockNo(current.Hashcode,
out var newBucketNo,
out var newLockNo,
newBuckets.Length,
newLocks.Length);
newBuckets[newBucketNo] = new(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(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 (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 is not 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 int Hashcode;
public readonly T Item;
public volatile Node Next;
public Node(T item, int hashcode, Node next)
{
Item = item;
Hashcode = hashcode;
Next = next;
}
}
}

View File

@ -1,185 +0,0 @@
#nullable disable
using Cloneable;
using NadekoBot.Common.Yml;
using SixLabors.ImageSharp.PixelFormats;
using System.Globalization;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
namespace NadekoBot.Common.Configs;
[Cloneable]
public sealed partial class BotConfig : ICloneable<BotConfig>
{
[Comment(@"DO NOT CHANGE")]
public int Version { get; set; } = 2;
[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(@"Only users who send a DM to the bot containing one of the specified words will get a DmHelpText response.
Case insensitive.
Leave empty to reply with DmHelpText to every DM.")]
public List<string> DmHelpTextKeywords { 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 .ropl command.
See RotatingStatuses submodule in Administration.")]
public bool RotateStatuses { get; set; }
public BotConfig()
{
var color = new ColorConfig();
Color = color;
DefaultLocale = new("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/nKYyqMK.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://nadeko.bot/commands"",
""inline"": false
},
{
""name"": ""Nadeko Support Server"",
""value"": ""https://discord.nadeko.bot/ "",
""inline"": true
}
]
}";
var blocked = new BlockedConfig();
Blocked = blocked;
Prefix = ".";
RotateStatuses = false;
GroupGreets = false;
DmHelpTextKeywords = new()
{
"help",
"commands",
"cmds",
"module",
"can you do"
};
}
// [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;
}
[Cloneable]
public sealed partial class BlockedConfig
{
public HashSet<string> Commands { get; set; }
public HashSet<string> Modules { get; set; }
public BlockedConfig()
{
Modules = new();
Commands = new();
}
}
[Cloneable]
public partial 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("00e584");
Error = Rgba32.ParseHex("ee281f");
Pending = Rgba32.ParseHex("faa61a");
}
}
public enum ConsoleOutputType
{
Normal = 0,
Simple = 1,
None = 2
}

View File

@ -1,198 +0,0 @@
#nullable disable
using NadekoBot.Common.Yml;
namespace NadekoBot.Common;
public sealed class Creds : IBotCredentials
{
[Comment(@"DO NOT CHANGE")]
public int Version { get; set; }
[Comment(@"Bot token. Do not share with anyone ever -> https://discordapp.com/developers/applications/")]
public string Token { get; set; }
[Comment(@"List of Ids of the users who have bot owner permissions
**DO NOT ADD PEOPLE YOU DON'T TRUST**")]
public ICollection<ulong> OwnerIds { get; set; }
[Comment("Keep this on 'true' unless you're sure your bot shouldn't use privileged intents or you're waiting to be accepted")]
public bool UsePrivilegedIntents { get; set; }
[Comment(@"The number of shards that the bot will running on.
Leave at 1 if you don't know what you're doing.")]
public int TotalShards { get; set; }
[Comment(
@"Login to https://console.cloud.google.com, create a new project, go to APIs & Services -> Library -> YouTube Data API and enable it.
Then, go to APIs and Services -> Credentials and click Create credentials -> API key.
Used only for Youtube Data Api (at the moment).")]
public string GoogleApiKey { get; set; }
[Comment(@"Settings for voting system for discordbots. Meant for use on global Nadeko.")]
public VotesSettings Votes { get; set; }
[Comment(@"Patreon auto reward system settings.
go to https://www.patreon.com/portal -> my clients -> create client")]
public PatreonSettings Patreon { get; set; }
[Comment(@"Api key for sending stats to DiscordBotList.")]
public string BotListToken { get; set; }
[Comment(@"Official cleverbot api key.")]
public string CleverbotApiKey { get; set; }
[Comment(@"Redis connection string. Don't change if you don't know what you're doing.")]
public string RedisOptions { get; set; }
[Comment(@"Database options. Don't change if you don't know what you're doing. Leave null for default values")]
public DbOptions Db { get; set; }
[Comment(@"Address and port of the coordinator endpoint. Leave empty for default.
Change only if you've changed the coordinator address or port.")]
public string CoordinatorUrl { get; set; }
[Comment(
@"Api key obtained on https://rapidapi.com (go to MyApps -> Add New App -> Enter Name -> Application key)")]
public string RapidApiKey { get; set; }
[Comment(@"https://locationiq.com api key (register and you will receive the token in the email).
Used only for .time command.")]
public string LocationIqApiKey { get; set; }
[Comment(@"https://timezonedb.com api key (register and you will receive the token in the email).
Used only for .time command")]
public string TimezoneDbApiKey { get; set; }
[Comment(@"https://pro.coinmarketcap.com/account/ api key. There is a free plan for personal use.
Used for cryptocurrency related commands.")]
public string CoinmarketcapApiKey { get; set; }
// [Comment(@"https://polygon.io/dashboard/api-keys api key. Free plan allows for 5 queries per minute.
// Used for stocks related commands.")]
// public string PolygonIoApiKey { get; set; }
[Comment(@"Api key used for Osu related commands. Obtain this key at https://osu.ppy.sh/p/api")]
public string OsuApiKey { get; set; }
[Comment(@"Optional Trovo client id.
You should use this if Trovo stream notifications stopped working or you're getting ratelimit errors.")]
public string TrovoClientId { get; set; }
[Comment(@"Obtain by creating an application at https://dev.twitch.tv/console/apps")]
public string TwitchClientId { get; set; }
[Comment(@"Obtain by creating an application at https://dev.twitch.tv/console/apps")]
public string TwitchClientSecret { get; set; }
[Comment(@"Command and args which will be used to restart the bot.
Only used if bot is executed directly (NOT through the coordinator)
placeholders:
{0} -> shard id
{1} -> total shards
Linux default
cmd: dotnet
args: ""NadekoBot.dll -- {0}""
Windows default
cmd: NadekoBot.exe
args: {0}")]
public RestartConfig RestartCommand { get; set; }
public Creds()
{
Version = 4;
Token = string.Empty;
UsePrivilegedIntents = true;
OwnerIds = new List<ulong>();
TotalShards = 1;
GoogleApiKey = string.Empty;
Votes = new(string.Empty, string.Empty, string.Empty, string.Empty);
Patreon = new(string.Empty, string.Empty, string.Empty, string.Empty);
BotListToken = string.Empty;
CleverbotApiKey = string.Empty;
RedisOptions = "localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password=";
Db = new()
{
Type = "sqlite",
ConnectionString = "Data Source=data/NadekoBot.db"
};
CoordinatorUrl = "http://localhost:3442";
RestartCommand = new();
}
public class DbOptions
{
[Comment(@"Database type. Only sqlite supported atm")]
public string Type { get; set; }
[Comment(@"Connection string. Will default to ""Data Source=data/NadekoBot.db""")]
public string ConnectionString { get; set; }
}
public sealed record PatreonSettings
{
public string ClientId { get; set; }
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
public string ClientSecret { get; set; }
[Comment(
@"Campaign ID of your patreon page. Go to your patreon page (make sure you're logged in) and type ""prompt('Campaign ID', window.patreon.bootstrap.creator.data.id);"" in the console. (ctrl + shift + i)")]
public string CampaignId { get; set; }
public PatreonSettings(
string accessToken,
string refreshToken,
string clientSecret,
string campaignId)
{
AccessToken = accessToken;
RefreshToken = refreshToken;
ClientSecret = clientSecret;
CampaignId = campaignId;
}
public PatreonSettings()
{
}
}
public sealed record VotesSettings
{
[Comment(@"top.gg votes service url
This is the url of your instance of the NadekoBot.Votes api
Example: https://votes.my.cool.bot.com")]
public string TopggServiceUrl { get; set; }
[Comment(@"Authorization header value sent to the TopGG service url with each request
This should be equivalent to the TopggKey in your NadekoBot.Votes api appsettings.json file")]
public string TopggKey { get; set; }
[Comment(@"discords.com votes service url
This is the url of your instance of the NadekoBot.Votes api
Example: https://votes.my.cool.bot.com")]
public string DiscordsServiceUrl { get; set; }
[Comment(@"Authorization header value sent to the Discords service url with each request
This should be equivalent to the DiscordsKey in your NadekoBot.Votes api appsettings.json file")]
public string DiscordsKey { get; set; }
public VotesSettings()
{
}
public VotesSettings(
string topggServiceUrl,
string topggKey,
string discordsServiceUrl,
string discordsKey)
{
TopggServiceUrl = topggServiceUrl;
TopggKey = topggKey;
DiscordsServiceUrl = discordsServiceUrl;
DiscordsKey = discordsKey;
}
}
}

View File

@ -1,34 +0,0 @@
#nullable disable
namespace NadekoBot;
public interface IBotCredentials
{
string Token { get; }
string GoogleApiKey { get; }
ICollection<ulong> OwnerIds { get; }
bool UsePrivilegedIntents { get; }
string RapidApiKey { get; }
Creds.DbOptions Db { get; }
string OsuApiKey { get; }
int TotalShards { get; }
Creds.PatreonSettings Patreon { get; }
string CleverbotApiKey { get; }
RestartConfig RestartCommand { get; }
Creds.VotesSettings Votes { get; }
string BotListToken { get; }
string RedisOptions { get; }
string LocationIqApiKey { get; }
string TimezoneDbApiKey { get; }
string CoinmarketcapApiKey { get; }
string TrovoClientId { get; }
string CoordinatorUrl { get; set; }
string TwitchClientId { get; set; }
string TwitchClientSecret { get; set; }
}
public class RestartConfig
{
public string Cmd { get; set; }
public string Args { get; set; }
}

View File

@ -1,23 +0,0 @@
#nullable disable
namespace NadekoBot;
public interface IEmbedBuilder
{
IEmbedBuilder WithDescription(string desc);
IEmbedBuilder WithTitle(string title);
IEmbedBuilder AddField(string title, object value, bool isInline = false);
IEmbedBuilder WithFooter(string text, string iconUrl = null);
IEmbedBuilder WithAuthor(string name, string iconUrl = null, string url = null);
IEmbedBuilder WithColor(EmbedColor color);
Embed Build();
IEmbedBuilder WithUrl(string url);
IEmbedBuilder WithImageUrl(string url);
IEmbedBuilder WithThumbnailUrl(string url);
}
public enum EmbedColor
{
Ok,
Pending,
Error
}

View File

@ -1,7 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public interface INadekoCommandOptions
{
void NormalizeOptions();
}

View File

@ -1,10 +0,0 @@
namespace NadekoBot.Common.ModuleBehaviors;
/// <summary>
/// Implemented by modules which block execution before anything is executed
/// </summary>
public interface IEarlyBehavior
{
int Priority { get; }
Task<bool> RunBehavior(IGuild guild, IUserMessage msg);
}

View File

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

View File

@ -1,8 +0,0 @@
namespace NadekoBot.Common.ModuleBehaviors;
public interface ILateBlocker
{
public int Priority { get; }
Task<bool> TryBlockLate(ICommandContext context, string moduleName, CommandInfo command);
}

View File

@ -1,9 +0,0 @@
namespace NadekoBot.Common.ModuleBehaviors;
/// <summary>
/// Last thing to be executed, won't stop further executions
/// </summary>
public interface ILateExecutor
{
Task LateExecute(IGuild guild, IUserMessage msg);
}

View File

@ -1,137 +0,0 @@
#nullable disable
using System.Globalization;
// ReSharper disable InconsistentNaming
namespace NadekoBot.Modules;
[UsedImplicitly(ImplicitUseTargetFlags.Default
| ImplicitUseTargetFlags.WithInheritors
| ImplicitUseTargetFlags.WithMembers)]
public abstract class NadekoModule : ModuleBase
{
protected CultureInfo Culture { get; set; }
// Injected by Discord.net
public IBotStrings Strings { get; set; }
public CommandHandler _cmdHandler { get; set; }
public ILocalization _localization { get; set; }
public IEmbedBuilderService _eb { get; set; }
protected string prefix
=> _cmdHandler.GetPrefix(ctx.Guild);
protected ICommandContext ctx
=> Context;
protected override void BeforeExecute(CommandInfo command)
=> Culture = _localization.GetCultureInfo(ctx.Guild?.Id);
protected string GetText(in LocStr data)
=> Strings.GetText(data, Culture);
public Task<IUserMessage> SendErrorAsync(string error)
=> ctx.Channel.SendErrorAsync(_eb, error);
public Task<IUserMessage> SendErrorAsync(
string title,
string error,
string url = null,
string footer = null)
=> ctx.Channel.SendErrorAsync(_eb, title, error, url, footer);
public Task<IUserMessage> SendConfirmAsync(string text)
=> ctx.Channel.SendConfirmAsync(_eb, text);
public Task<IUserMessage> SendConfirmAsync(
string title,
string text,
string url = null,
string footer = null)
=> ctx.Channel.SendConfirmAsync(_eb, title, text, url, footer);
public Task<IUserMessage> SendPendingAsync(string text)
=> ctx.Channel.SendPendingAsync(_eb, text);
public Task<IUserMessage> ErrorLocalizedAsync(LocStr str)
=> SendErrorAsync(GetText(str));
public Task<IUserMessage> PendingLocalizedAsync(LocStr str)
=> SendPendingAsync(GetText(str));
public Task<IUserMessage> ConfirmLocalizedAsync(LocStr str)
=> SendConfirmAsync(GetText(str));
public Task<IUserMessage> ReplyErrorLocalizedAsync(LocStr str)
=> SendErrorAsync($"{Format.Bold(ctx.User.ToString())} {GetText(str)}");
public Task<IUserMessage> ReplyPendingLocalizedAsync(LocStr str)
=> SendPendingAsync($"{Format.Bold(ctx.User.ToString())} {GetText(str)}");
public Task<IUserMessage> ReplyConfirmLocalizedAsync(LocStr str)
=> SendConfirmAsync($"{Format.Bold(ctx.User.ToString())} {GetText(str)}");
public async Task<bool> PromptUserConfirmAsync(IEmbedBuilder embed)
{
embed.WithPendingColor().WithFooter("yes/no");
var msg = await ctx.Channel.EmbedAsync(embed);
try
{
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id);
input = input?.ToUpperInvariant();
if (input != "YES" && input != "Y")
return false;
return true;
}
finally
{
_ = 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)) != userInputTask.Task)
return null;
return await userInputTask.Task;
}
finally
{
dsc.MessageReceived -= MessageReceived;
}
Task MessageReceived(SocketMessage arg)
{
_ = Task.Run(() =>
{
if (arg is not SocketUserMessage userMsg
|| userMsg.Channel is not ITextChannel
|| 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 NadekoModule<TService> : NadekoModule
{
public TService _service { get; set; }
}

View File

@ -1,69 +0,0 @@
#nullable disable
using System.Security.Cryptography;
namespace NadekoBot.Common;
public class NadekoRandom : Random
{
private readonly RandomNumberGenerator _rng;
public NadekoRandom()
=> _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

@ -1,46 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public class OldCreds
{
public string Token { get; set; } = string.Empty;
public ulong[] OwnerIds { get; set; } = new ulong[1];
public string LoLApiKey { get; set; } = string.Empty;
public string GoogleApiKey { get; set; } = string.Empty;
public string MashapeKey { get; set; } = string.Empty;
public string OsuApiKey { get; set; } = string.Empty;
public string SoundCloudClientId { get; set; } = string.Empty;
public string CleverbotApiKey { get; set; } = string.Empty;
public string CarbonKey { get; set; } = string.Empty;
public int TotalShards { get; set; } = 1;
public string PatreonAccessToken { get; set; } = string.Empty;
public string PatreonCampaignId { get; set; } = "334038";
public RestartConfig RestartCommand { get; set; }
public string ShardRunCommand { get; set; } = string.Empty;
public string ShardRunArguments { get; set; } = string.Empty;
public int? ShardRunPort { get; set; }
public string MiningProxyUrl { get; set; } = string.Empty;
public string MiningProxyCreds { get; set; } = string.Empty;
public string BotListToken { get; set; } = string.Empty;
public string TwitchClientId { get; set; } = string.Empty;
public string VotesToken { get; set; } = string.Empty;
public string VotesUrl { get; set; } = string.Empty;
public string RedisOptions { get; set; } = string.Empty;
public string LocationIqApiKey { get; set; } = string.Empty;
public string TimezoneDbApiKey { get; set; } = string.Empty;
public string CoinmarketcapApiKey { get; set; } = string.Empty;
public class RestartConfig
{
public string Cmd { get; set; }
public string Args { get; set; }
public RestartConfig(string cmd, string args)
{
Cmd = cmd;
Args = args;
}
}
}

View File

@ -1,47 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public class OldImageUrls
{
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

@ -1,25 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public static class PlatformHelper
{
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 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 >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS)
{
processorCount = Environment.ProcessorCount;
lastProcessorCountRefreshTicks = now;
}
return processorCount;
}
}
}

View File

@ -1,163 +0,0 @@
#nullable disable
using NadekoBot.Modules.Administration.Services;
using System.Text.RegularExpressions;
namespace NadekoBot.Common;
public class ReplacementBuilder
{
private static readonly Regex _rngRegex = new("%rng(?:(?<from>(?:-)?\\d+)-(?<to>(?:-)?\\d+))?%",
RegexOptions.Compiled);
private readonly ConcurrentDictionary<Regex, Func<Match, string>> _regex = new();
private readonly ConcurrentDictionary<string, Func<string>> _reps = new();
public ReplacementBuilder()
=> WithRngRegex();
public ReplacementBuilder WithDefault(
IUser usr,
IMessageChannel ch,
SocketGuild g,
DiscordSocketClient client)
=> 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)
{
_reps.TryAdd("%bot.mention%", () => client.CurrentUser.Mention);
return this;
}
public ReplacementBuilder WithClient(DiscordSocketClient client)
{
WithMention(client);
_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)
{
_reps.TryAdd("%server%", () => g is null ? "DM" : g.Name);
_reps.TryAdd("%server.id%", () => g is null ? "DM" : g.Id.ToString());
_reps.TryAdd("%server.name%", () => g is null ? "DM" : g.Name);
_reps.TryAdd("%server.members%", () => g is { } sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server.boosters%", () => g.PremiumSubscriptionCount.ToString());
_reps.TryAdd("%server.boost_level%", () => ((int)g.PremiumTier).ToString());
_reps.TryAdd("%server.time%",
() =>
{
var to = TimeZoneInfo.Local;
if (g is not 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)
{
_reps.TryAdd("%channel%", () => ch.Name);
_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 dd.MM.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)
{
WithManyUsers(new[] { user });
return this;
}
public ReplacementBuilder WithManyUsers(IEnumerable<IUser> users)
{
_reps.TryAdd("%user%", () => string.Join(" ", users.Select(user => user.Mention)));
_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)
{
_reps.TryAdd("%shard.servercount%", () => c.Guilds.Count.ToString());
_reps.TryAdd("%shard.usercount%", () => c.Guilds.Sum(g => g.MemberCount).ToString());
_reps.TryAdd("%shard.id%", () => c.ShardId.ToString());
return this;
}
public ReplacementBuilder WithRngRegex()
{
var rng = new NadekoRandom();
_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()
=> new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray());
public ReplacementBuilder WithProviders(IEnumerable<IPlaceholderProvider> phProviders)
{
foreach (var provider in phProviders)
foreach (var ovr in provider.GetPlaceholders())
_reps.TryAdd(ovr.Name, ovr.Func);
return this;
}
}

View File

@ -1,95 +0,0 @@
#nullable disable
using System.Text.RegularExpressions;
namespace NadekoBot.Common;
public class Replacer
{
private readonly IEnumerable<(Regex Regex, Func<Match, string> Replacement)> _regex;
private readonly IEnumerable<(string Key, Func<string> Text)> _replacements;
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 SmartText Replace(SmartText data)
=> data switch
{
SmartEmbedText embedData => Replace(embedData),
SmartPlainText plain => Replace(plain),
_ => throw new ArgumentOutOfRangeException(nameof(data), "Unsupported argument type")
};
public SmartPlainText Replace(SmartPlainText plainText)
=> Replace(plainText.Text);
public SmartEmbedText Replace(SmartEmbedText embedData)
{
var newEmbedData = new SmartEmbedText
{
PlainText = Replace(embedData.PlainText),
Description = Replace(embedData.Description),
Title = Replace(embedData.Title),
Thumbnail = Replace(embedData.Thumbnail),
Image = Replace(embedData.Image),
Url = Replace(embedData.Url)
};
if (embedData.Author is not null)
{
newEmbedData.Author = new()
{
Name = Replace(embedData.Author.Name),
IconUrl = Replace(embedData.Author.IconUrl)
};
}
if (embedData.Fields is not null)
{
var fields = new List<SmartTextEmbedField>();
foreach (var f in embedData.Fields)
{
var newF = new SmartTextEmbedField
{
Name = Replace(f.Name),
Value = Replace(f.Value),
Inline = f.Inline
};
fields.Add(newF);
}
newEmbedData.Fields = fields.ToArray();
}
if (embedData.Footer is not null)
{
newEmbedData.Footer = new()
{
Text = Replace(embedData.Footer.Text),
IconUrl = Replace(embedData.Footer.IconUrl)
};
}
newEmbedData.Color = embedData.Color;
return newEmbedData;
}
}

View File

@ -1,43 +0,0 @@
#nullable disable
using System;
namespace NadekoBot.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)
=> new(num);
public static implicit operator long(ShmartNumber num)
=> num.Value;
public static implicit operator ShmartNumber(int num)
=> new(num);
public override string ToString()
=> Value.ToString();
public override bool Equals(object obj)
=> obj is ShmartNumber sn && Equals(sn);
public bool Equals(ShmartNumber other)
=> other.Value == Value;
public override int GetHashCode()
=> Value.GetHashCode() ^ Input.GetHashCode(StringComparison.InvariantCulture);
public static bool operator ==(ShmartNumber left, ShmartNumber right)
=> left.Equals(right);
public static bool operator !=(ShmartNumber left, ShmartNumber right)
=> !(left == right);
}

View File

@ -1,60 +0,0 @@
#nullable disable
using Newtonsoft.Json;
namespace NadekoBot;
public abstract record SmartText
{
public bool IsEmbed
=> this is SmartEmbedText;
public bool IsPlainText
=> this is SmartPlainText;
public static SmartText operator +(SmartText text, string input)
=> text switch
{
SmartEmbedText set => set with
{
PlainText = set.PlainText + input
},
SmartPlainText spt => new SmartPlainText(spt.Text + input),
_ => throw new ArgumentOutOfRangeException(nameof(text))
};
public static SmartText operator +(string input, SmartText text)
=> text switch
{
SmartEmbedText set => set with
{
PlainText = input + set.PlainText
},
SmartPlainText spt => new SmartPlainText(input + spt.Text),
_ => throw new ArgumentOutOfRangeException(nameof(text))
};
public static SmartText CreateFrom(string input)
{
if (string.IsNullOrWhiteSpace(input) || !input.TrimStart().StartsWith("{"))
return new SmartPlainText(input);
try
{
var smartEmbedText = JsonConvert.DeserializeObject<SmartEmbedText>(input);
if (smartEmbedText is null)
throw new FormatException();
smartEmbedText.NormalizeFields();
if (!smartEmbedText.IsValid)
return new SmartPlainText(input);
return smartEmbedText;
}
catch
{
return new SmartPlainText(input);
}
}
}

View File

@ -1,95 +0,0 @@
#nullable disable
namespace NadekoBot.Common;
public sealed class ReactionEventWrapper : IDisposable
{
public event Action<SocketReaction> OnReactionAdded = delegate { };
public event Action<SocketReaction> OnReactionRemoved = delegate { };
public event Action OnReactionsCleared = delegate { };
public IUserMessage Message { get; }
private readonly DiscordSocketClient _client;
private bool disposing;
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;
}
public void Dispose()
{
if (disposing)
return;
disposing = true;
UnsubAll();
}
private Task Discord_ReactionsCleared(Cacheable<IUserMessage, ulong> msg, Cacheable<IMessageChannel, ulong> channel)
{
Task.Run(() =>
{
try
{
if (msg.Id == Message.Id)
OnReactionsCleared?.Invoke();
}
catch { }
});
return Task.CompletedTask;
}
private Task Discord_ReactionRemoved(
Cacheable<IUserMessage, ulong> msg,
Cacheable<IMessageChannel, ulong> cacheable,
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,
Cacheable<IMessageChannel, ulong> cacheable,
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;
}
}

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