mirror of
https://gitlab.com/Kwoth/nadekobot.git
synced 2025-09-11 09:48:26 -04:00
Compare commits
83 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
23b3ad5837 | ||
|
18619b4d3a | ||
|
ef06388335 | ||
|
d1db54498b | ||
|
eef5b3f948 | ||
|
d86b5b2b6c | ||
|
127a46a9b8 | ||
|
a7e1e8a982 | ||
|
b0ac35b82e | ||
|
367135be6a | ||
|
f69f8548b0 | ||
|
449dbafff7 | ||
|
afba004d85 | ||
|
ef4d38bc87 | ||
|
96851c7c2d | ||
|
41ae182373 | ||
|
9bf5a5a3cd | ||
|
bab23c25a5 | ||
|
0ba8555f56 | ||
|
340c5b2268 | ||
|
77e8c66b73 | ||
|
9d9f8f7f98 | ||
|
77358a563d | ||
|
82a48b101b | ||
|
6ebe321de9 | ||
|
b4fec10ee6 | ||
|
42b9a01550 | ||
|
5f94b20015 | ||
|
201aa45c6b | ||
|
97ae7b5a5b | ||
|
9b09f223d9 | ||
|
2caf406254 | ||
|
ce5e04b398 | ||
|
775487ad47 | ||
|
41e4936f52 | ||
|
d831a116d9 | ||
|
8f43b44677 | ||
|
93df4f3bf3 | ||
|
073b832065 | ||
|
a01e580e03 | ||
|
6124e2fab5 | ||
|
4dd31d6a0b | ||
|
e8706d4006 | ||
|
140cc43c98 | ||
|
26b7149435 | ||
|
b354ee7269 | ||
|
b829ca0109 | ||
|
37acdb81e8 | ||
|
a9aea65134 | ||
|
5c03c5ba16 | ||
|
42f00c08fa | ||
|
598d3b8967 | ||
|
8df41c749b | ||
|
0eaa8be2d2 | ||
|
bdbe76f9f8 | ||
|
08b609a4b4 | ||
|
42d13b32b2 | ||
|
096ada367f | ||
|
0fed33ebda | ||
|
cb9e918681 | ||
|
bbf167df4d | ||
|
595a2b401c | ||
|
5713e8414e | ||
|
a551caf0da | ||
|
b13f05c4c0 | ||
|
6d6a3a811f | ||
|
fb4aac9f0d | ||
|
a98981de86 | ||
|
9ef3646711 | ||
|
9c174b8b6f | ||
|
657c1e461c | ||
|
f5a4a698bd | ||
|
8112337aaf | ||
|
73f7394e31 | ||
|
987d88287a | ||
|
9dc783b36f | ||
|
13741b8317 | ||
|
313ca2674e | ||
|
98956481e9 | ||
|
51e887fe04 | ||
|
8ceab64b96 | ||
|
92b8511cf1 | ||
|
a6a052571e |
@@ -14,8 +14,16 @@ variables:
|
|||||||
tests: "NadekoBot.Tests"
|
tests: "NadekoBot.Tests"
|
||||||
LINUX_X64_OUTPUT_DIR: "nadekobot-linux-x64"
|
LINUX_X64_OUTPUT_DIR: "nadekobot-linux-x64"
|
||||||
LINUX_X64_RELEASE: "$CI_COMMIT_TAG-linux-x64-build.tar"
|
LINUX_X64_RELEASE: "$CI_COMMIT_TAG-linux-x64-build.tar"
|
||||||
|
LINUX_ARM64_OUTPUT_DIR: "nadekobot-linux-arm64"
|
||||||
|
LINUX_ARM64_RELEASE: "$CI_COMMIT_TAG-linux-arm64-build.tar"
|
||||||
|
MACOS_X64_OUTPUT_DIR: "nadekobot-osx-x64"
|
||||||
|
MACOS_X64_RELEASE: "$CI_COMMIT_TAG-osx-x64-build.tar"
|
||||||
|
MACOS_ARM64_OUTPUT_DIR: "nadekobot-osx-arm64"
|
||||||
|
MACOS_ARM64_RELEASE: "$CI_COMMIT_TAG-osx-arm64-build.tar"
|
||||||
WIN_X64_OUTPUT_DIR: "nadekobot-windows-x64"
|
WIN_X64_OUTPUT_DIR: "nadekobot-windows-x64"
|
||||||
WIN_X64_RELEASE: "$CI_COMMIT_TAG-windows-x64-build.zip"
|
WIN_X64_RELEASE: "$CI_COMMIT_TAG-windows-x64-build.zip"
|
||||||
|
WIN_ARM64_OUTPUT_DIR: "nadekobot-windows-arm64"
|
||||||
|
WIN_ARM64_RELEASE: "$CI_COMMIT_TAG-windows-arm64-build.zip"
|
||||||
PACKAGE_REGISTRY_URL: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/NadekoBot-build/${CI_COMMIT_TAG}"
|
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_OUTPUT_DIR: "nadeko-installers/${CI_COMMIT_TAG}"
|
||||||
INSTALLER_FILE_NAME: "nadeko-setup-${CI_COMMIT_TAG}.exe"
|
INSTALLER_FILE_NAME: "nadeko-setup-${CI_COMMIT_TAG}.exe"
|
||||||
@@ -24,11 +32,19 @@ build:
|
|||||||
stage: build
|
stage: build
|
||||||
script:
|
script:
|
||||||
- "dotnet publish -c Release -r linux-x64 --self-contained -o $LINUX_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
- "dotnet publish -c Release -r linux-x64 --self-contained -o $LINUX_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
|
- "dotnet publish -c Release -r linux-arm64 --self-contained -o $LINUX_ARM64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
- "dotnet publish -c Release -r win7-x64 --self-contained -o $WIN_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
- "dotnet publish -c Release -r win7-x64 --self-contained -o $WIN_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
|
- "dotnet publish -c Release -r win7-arm64 --self-contained -o $WIN_ARM64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
|
- "dotnet publish -c Release -r osx-x64 --self-contained -o $MACOS_X64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
|
- "dotnet publish -c Release -r osx-arm64 --self-contained -o $MACOS_ARM64_OUTPUT_DIR src/NadekoBot/NadekoBot.csproj"
|
||||||
artifacts:
|
artifacts:
|
||||||
paths:
|
paths:
|
||||||
- "$LINUX_X64_OUTPUT_DIR/"
|
- "$LINUX_X64_OUTPUT_DIR/"
|
||||||
|
- "$LINUX_ARM64_OUTPUT_DIR/"
|
||||||
- "$WIN_X64_OUTPUT_DIR/"
|
- "$WIN_X64_OUTPUT_DIR/"
|
||||||
|
- "$WIN_ARM64_OUTPUT_DIR/"
|
||||||
|
- "$MACOS_X64_OUTPUT_DIR/"
|
||||||
|
- "$MACOS_ARM64_OUTPUT_DIR/"
|
||||||
|
|
||||||
upload-builds:
|
upload-builds:
|
||||||
stage: upload-builds
|
stage: upload-builds
|
||||||
@@ -38,12 +54,23 @@ upload-builds:
|
|||||||
script:
|
script:
|
||||||
- apk add --no-cache curl tar zip
|
- apk add --no-cache curl tar zip
|
||||||
- "tar cvf $LINUX_X64_RELEASE $LINUX_X64_OUTPUT_DIR/*"
|
- "tar cvf $LINUX_X64_RELEASE $LINUX_X64_OUTPUT_DIR/*"
|
||||||
|
- "tar cvf $LINUX_ARM64_RELEASE $LINUX_ARM64_OUTPUT_DIR/*"
|
||||||
|
- "tar cvf $MACOS_X64_RELEASE $MACOS_X64_OUTPUT_DIR/*"
|
||||||
|
- "tar cvf $MACOS_ARM64_RELEASE $MACOS_ARM64_OUTPUT_DIR/*"
|
||||||
- "zip -r $WIN_X64_RELEASE $WIN_X64_OUTPUT_DIR/*"
|
- "zip -r $WIN_X64_RELEASE $WIN_X64_OUTPUT_DIR/*"
|
||||||
|
- "zip -r $WIN_ARM64_RELEASE $WIN_ARM64_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 $LINUX_X64_RELEASE $PACKAGE_REGISTRY_URL/$LINUX_X64_RELEASE
|
||||||
|
- |
|
||||||
|
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $LINUX_ARM64_RELEASE $PACKAGE_REGISTRY_URL/$LINUX_ARM64_RELEASE
|
||||||
- |
|
- |
|
||||||
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $WIN_X64_RELEASE $PACKAGE_REGISTRY_URL/$WIN_X64_RELEASE
|
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $WIN_X64_RELEASE $PACKAGE_REGISTRY_URL/$WIN_X64_RELEASE
|
||||||
|
- |
|
||||||
|
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $WIN_ARM64_RELEASE $PACKAGE_REGISTRY_URL/$WIN_ARM64_RELEASE
|
||||||
|
- |
|
||||||
|
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $MACOS_X64_RELEASE $PACKAGE_REGISTRY_URL/$MACOS_X64_RELEASE
|
||||||
|
- |
|
||||||
|
curl --header "JOB-TOKEN: ${CI_JOB_TOKEN}" --upload-file $MACOS_ARM64_RELEASE $PACKAGE_REGISTRY_URL/$MACOS_ARM64_RELEASE
|
||||||
release:
|
release:
|
||||||
stage: release
|
stage: release
|
||||||
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
||||||
@@ -53,7 +80,11 @@ release:
|
|||||||
- |
|
- |
|
||||||
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 \
|
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\":\"${LINUX_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${LINUX_X64_RELEASE}\"}" \
|
||||||
--assets-link "{\"name\":\"${WIN_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${WIN_X64_RELEASE}\"}"
|
--assets-link "{\"name\":\"${LINUX_ARM64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${LINUX_ARM64_RELEASE}\"}" \
|
||||||
|
--assets-link "{\"name\":\"${WIN_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${WIN_X64_RELEASE}\"}" \
|
||||||
|
--assets-link "{\"name\":\"${WIN_ARM64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${WIN_ARM64_RELEASE}\"}" \
|
||||||
|
--assets-link "{\"name\":\"${MACOS_X64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${MACOS_X64_RELEASE}\"}" \
|
||||||
|
--assets-link "{\"name\":\"${MACOS_ARM64_RELEASE}\",\"url\":\"${PACKAGE_REGISTRY_URL}/${MACOS_ARM64_RELEASE}\"}"
|
||||||
|
|
||||||
test:
|
test:
|
||||||
stage: test
|
stage: test
|
||||||
|
106
CHANGELOG.md
106
CHANGELOG.md
@@ -2,6 +2,112 @@
|
|||||||
|
|
||||||
Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.com/en/1.0.0/) except date format. a-c-f-r-o
|
Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.com/en/1.0.0/) except date format. a-c-f-r-o
|
||||||
|
|
||||||
|
## [4.3.22] - 23.04.2023
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added `.setbanner` command (thx cata)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Fixed pagination error due to a missing emoji
|
||||||
|
|
||||||
|
|
||||||
|
## [4.3.21] - 19.04.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Possible fix for a duplicate in `.h bank`
|
||||||
|
- Fixed `.stock` command
|
||||||
|
- Fixed `.clubapply` and `.clubaccept`
|
||||||
|
- Removed some redundant discriminators
|
||||||
|
|
||||||
|
## [4.3.20] - 20.01.2024
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Fixed `.config searches followedStreams.maxCount` not working
|
||||||
|
|
||||||
|
## [4.3.19] - 20.01.2024
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added `followedStreams.maxCount` to `searches.yml` which lets bot owners change the default of 10 per server
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Improvements to GPT ChatterBot (thx alexandra)
|
||||||
|
- Add a personality prompt to tweak the way chatgpt bot behaves
|
||||||
|
- Added Chat history support to chatgpt ChatterBot
|
||||||
|
- Chatgpt token usage now correctly calculated
|
||||||
|
- More chatgpt configs in `games.yml`
|
||||||
|
|
||||||
|
## [4.3.18] - 26.12.2023
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added `.cacheusers` command (thx Kotz)
|
||||||
|
- Added `.clubreject` which lets you reject club applications
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Updated discord lib, there should be less console errors now
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed `icon_url` when using `.showembed`
|
||||||
|
- Fixed `.quoteshow` not showing sometimes (thx Cata)
|
||||||
|
- Notifications will no longer be sent if dms are off when using `.give`
|
||||||
|
- Users should no longer be able to apply to clubs while in a club already (especially not to the same club they're already in)
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- `.revimg` and `.revav` as google removed reverse image search
|
||||||
|
|
||||||
|
## [4.3.17] - 06.09.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fix to waifu gifts being character limited
|
||||||
|
- Fixes UserUpdated and UserPresence not correctly ignoring users that are logignored
|
||||||
|
- Added Trim() to activity names since apparently some activities have trailing spaces.
|
||||||
|
|
||||||
|
## [4.3.16] - 24.05.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed missing events from `.logevents`
|
||||||
|
- Fixed `.log` thread deleted and thread created events not working properly
|
||||||
|
|
||||||
|
## [4.3.15] - 21.05.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed -w 0 in trivia
|
||||||
|
- Fixed `.rps` amount field in the response
|
||||||
|
- Fixed `.showembed` output
|
||||||
|
- Fixed bank award's incorrect output message
|
||||||
|
|
||||||
|
## [4.3.14] - 02.04.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed voice hearbeat issue
|
||||||
|
- `.banktake` had ok/error responses flipped. No functional change
|
||||||
|
- PermRole should deny messages in threads todo
|
||||||
|
- Fixed chucknorris jokes
|
||||||
|
- `.logserver` will now
|
||||||
|
|
||||||
|
## [4.3.13] - 20.02.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed `.log userpresence`
|
||||||
|
- `.q` will now use `yt-dlp` if anything other than `ytProvider: Ytdl` is set in `data/searches.yml`
|
||||||
|
- Fixed Title links on some embeds
|
||||||
|
|
||||||
|
## [4.3.12] - 12.02.2023
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed `.betstats` not working on european locales
|
||||||
|
- Timed `.ban` will work on users who are not in the server
|
||||||
|
- Fixed some bugs in the medusa system
|
||||||
|
|
||||||
## [4.3.11] - 21.01.2023
|
## [4.3.11] - 21.01.2023
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@@ -28,12 +28,11 @@ WORKDIR /app
|
|||||||
RUN set -xe; \
|
RUN set -xe; \
|
||||||
useradd -m nadeko; \
|
useradd -m nadeko; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y --no-install-recommends libopus0 libsodium23 libsqlite3-0 curl ffmpeg python3 python3-pip sudo; \
|
apt-get install -y --no-install-recommends libopus0 libsodium23 libsqlite3-0 curl ffmpeg python3 sudo; \
|
||||||
update-alternatives --install /usr/bin/python python /usr/bin/python3.9 1; \
|
update-alternatives --install /usr/bin/python python /usr/bin/python3.9 1; \
|
||||||
echo 'Defaults>nadeko env_keep+="ASPNETCORE_* DOTNET_* NadekoBot_* shard_id total_shards TZ"' > /etc/sudoers.d/nadeko; \
|
echo 'Defaults>nadeko env_keep+="ASPNETCORE_* DOTNET_* NadekoBot_* shard_id total_shards TZ"' > /etc/sudoers.d/nadeko; \
|
||||||
pip3 install --no-cache-dir --upgrade youtube-dl; \
|
curl -Lo /usr/local/bin/yt-dlp https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp; \
|
||||||
apt-get purge -y python3-pip; \
|
chmod a+rx /usr/local/bin/yt-dlp; \
|
||||||
chmod +x /usr/local/bin/youtube-dl; \
|
|
||||||
apt-get autoremove -y; \
|
apt-get autoremove -y; \
|
||||||
apt-get autoclean -y
|
apt-get autoclean -y
|
||||||
|
|
||||||
|
23
docker-compose.yml
Normal file
23
docker-compose.yml
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
version: "3.7"
|
||||||
|
|
||||||
|
services:
|
||||||
|
nadeko:
|
||||||
|
image: insert-image-name-here:latest
|
||||||
|
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:/app/conf: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
|
@@ -24,6 +24,10 @@ The list below is not complete. Use commands above to see up-to-date list for yo
|
|||||||
|
|
||||||
`trivia.min_win_req` - Restricts a user's ability to make a trivia game with a win requirement less than the set value.
|
`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.
|
`trivia.currency_reward` - Sets the amount of currency a user will win if they place first in a completed trivia game.
|
||||||
|
`hangman.currency_reward` - Sets the amount of currency a user will win if they win a game of hangman.
|
||||||
|
`chatbot` - Sets which chatbot API the bot should use, values: `gpt3`, `cleverbot`.
|
||||||
|
`gpt.model` - Sets which GPT-3 model the bot should use, values: `ada001`, `babbage001`, `curie001`, `davinci003`.
|
||||||
|
`gpt.max_tokens` - Sets the limit of tokens GPT-3 can use per call. Find out more about tokens [here](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them).
|
||||||
|
|
||||||
*more settings may be available in `data/games.yml` file*
|
*more settings may be available in `data/games.yml` file*
|
||||||
|
|
||||||
|
@@ -20,7 +20,7 @@ It is recommended that you use **Ubuntu 20.04**, as there have been nearly no pr
|
|||||||
|
|
||||||
##### Compatible operating systems:
|
##### Compatible operating systems:
|
||||||
|
|
||||||
- Ubuntu: 16.04, 18.04, 20.04, 21.04, 21.10
|
- Ubuntu: 16.04, 18.04, 20.04
|
||||||
- Mint: 19, 20
|
- Mint: 19, 20
|
||||||
- Debian: 10, 11
|
- Debian: 10, 11
|
||||||
- CentOS: 7
|
- CentOS: 7
|
||||||
|
@@ -123,7 +123,7 @@ 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`.
|
- [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`.
|
- [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/
|
[Updater]: https://dl.nadeko.bot/v3/
|
||||||
[Notepad++]: https://notepad-plus-plus.org/
|
[Notepad++]: https://notepad-plus-plus.org/
|
||||||
[.net]: https://dotnet.microsoft.com/download/dotnet/5.0
|
[.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
|
[Redis]: https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi
|
||||||
|
@@ -68,11 +68,6 @@ Some features have their own specific placeholders which are noted in that featu
|
|||||||
- `%ban.reason%` - Reason for the ban, if provided
|
- `%ban.reason%` - Reason for the ban, if provided
|
||||||
- `%ban.duration%` - Duration of the ban in the form Days.Hours:Minutes (6.05:04)
|
- `%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 stats placeholders
|
||||||
|
|
||||||
- `%shard.servercount%` - Server count on current shard
|
- `%shard.servercount%` - Server count on current shard
|
||||||
@@ -89,6 +84,5 @@ Some features have their own specific placeholders which are noted in that featu
|
|||||||
|
|
||||||
- `%rngX-Y%` - Returns a random number between X and Y
|
- `%rngX-Y%` - Returns a random number between X and Y
|
||||||
- `%target%` - Returns anything the user has written after the trigger (only works on Expressions)
|
- `%target%` - Returns anything the user has written after the trigger (only works on Expressions)
|
||||||
- `%img:stuff%` - Returns an `imgur.com` search for "stuff" (only works on Expressions)
|
|
||||||
|
|
||||||

|

|
||||||
|
@@ -12,7 +12,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Discord.Net.Core" Version="3.104.0" />
|
<PackageReference Include="Discord.Net.Core" Version="3.204.0" />
|
||||||
<PackageReference Include="Serilog" Version="2.11.0" />
|
<PackageReference Include="Serilog" Version="2.11.0" />
|
||||||
<PackageReference Include="YamlDotNet" Version="11.2.1" />
|
<PackageReference Include="YamlDotNet" Version="11.2.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
@@ -10,7 +10,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" PrivateAssets="all" />
|
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1" PrivateAssets="all" />
|
||||||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
|
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" PrivateAssets="all" GeneratePathProperty="true" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" PrivateAssets="all" GeneratePathProperty="true" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
|
@@ -54,6 +54,9 @@ go to https://www.patreon.com/portal -> my clients -> create client")]
|
|||||||
[Comment(@"Official cleverbot api key.")]
|
[Comment(@"Official cleverbot api key.")]
|
||||||
public string CleverbotApiKey { get; set; }
|
public string CleverbotApiKey { get; set; }
|
||||||
|
|
||||||
|
[Comment(@"Official GPT-3 api key.")]
|
||||||
|
public string Gpt3ApiKey { get; set; }
|
||||||
|
|
||||||
[Comment(@"Which cache implementation should bot use.
|
[Comment(@"Which cache implementation should bot use.
|
||||||
'memory' - Cache will be in memory of the bot's process itself. Only use this on bots with a single shard. When the bot is restarted the cache is reset.
|
'memory' - Cache will be in memory of the bot's process itself. Only use this on bots with a single shard. When the bot is restarted the cache is reset.
|
||||||
'redis' - Uses redis (which needs to be separately downloaded and installed). The cache will persist through bot restarts. You can configure connection string in creds.yml")]
|
'redis' - Uses redis (which needs to be separately downloaded and installed). The cache will persist through bot restarts. You can configure connection string in creds.yml")]
|
||||||
@@ -118,7 +121,7 @@ Windows default
|
|||||||
|
|
||||||
public Creds()
|
public Creds()
|
||||||
{
|
{
|
||||||
Version = 6;
|
Version = 7;
|
||||||
Token = string.Empty;
|
Token = string.Empty;
|
||||||
UsePrivilegedIntents = true;
|
UsePrivilegedIntents = true;
|
||||||
OwnerIds = new List<ulong>();
|
OwnerIds = new List<ulong>();
|
||||||
@@ -128,6 +131,7 @@ Windows default
|
|||||||
Patreon = new(string.Empty, string.Empty, string.Empty, string.Empty);
|
Patreon = new(string.Empty, string.Empty, string.Empty, string.Empty);
|
||||||
BotListToken = string.Empty;
|
BotListToken = string.Empty;
|
||||||
CleverbotApiKey = string.Empty;
|
CleverbotApiKey = string.Empty;
|
||||||
|
Gpt3ApiKey = string.Empty;
|
||||||
BotCache = BotCacheImplemenation.Memory;
|
BotCache = BotCacheImplemenation.Memory;
|
||||||
RedisOptions = "localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password=";
|
RedisOptions = "localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password=";
|
||||||
Db = new()
|
Db = new()
|
||||||
|
@@ -14,6 +14,7 @@ public interface IBotCredentials
|
|||||||
int TotalShards { get; }
|
int TotalShards { get; }
|
||||||
Creds.PatreonSettings Patreon { get; }
|
Creds.PatreonSettings Patreon { get; }
|
||||||
string CleverbotApiKey { get; }
|
string CleverbotApiKey { get; }
|
||||||
|
string Gpt3ApiKey { get; }
|
||||||
RestartConfig RestartCommand { get; }
|
RestartConfig RestartCommand { get; }
|
||||||
Creds.VotesSettings Votes { get; }
|
Creds.VotesSettings Votes { get; }
|
||||||
string BotListToken { get; }
|
string BotListToken { get; }
|
||||||
|
@@ -459,6 +459,9 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
|
|||||||
pb.WithIsMultiple(paramData.IsParams)
|
pb.WithIsMultiple(paramData.IsParams)
|
||||||
.WithIsOptional(paramData.IsOptional)
|
.WithIsOptional(paramData.IsOptional)
|
||||||
.WithIsRemainder(paramData.IsLeftover);
|
.WithIsRemainder(paramData.IsLeftover);
|
||||||
|
|
||||||
|
if (paramData.IsOptional)
|
||||||
|
pb.WithDefault(paramData.DefaultValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||||
@@ -800,6 +803,7 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
|
|||||||
|
|
||||||
var leftoverAttribute = pi.GetCustomAttribute<leftoverAttribute>(true);
|
var leftoverAttribute = pi.GetCustomAttribute<leftoverAttribute>(true);
|
||||||
var hasDefaultValue = pi.HasDefaultValue;
|
var hasDefaultValue = pi.HasDefaultValue;
|
||||||
|
var defaultValue = pi.DefaultValue;
|
||||||
var isLeftover = leftoverAttribute != null;
|
var isLeftover = leftoverAttribute != null;
|
||||||
var isParams = pi.GetCustomAttribute<ParamArrayAttribute>() is not null;
|
var isParams = pi.GetCustomAttribute<ParamArrayAttribute>() is not null;
|
||||||
var paramType = pi.ParameterType;
|
var paramType = pi.ParameterType;
|
||||||
@@ -857,7 +861,7 @@ public sealed class MedusaLoaderService : IMedusaLoaderService, IReadyExecutor,
|
|||||||
throw new ArgumentException("Leftover attribute error.");
|
throw new ArgumentException("Leftover attribute error.");
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdParams.Add(new ParamData(paramType, paramName, hasDefaultValue, isLeftover, isParams));
|
cmdParams.Add(new ParamData(paramType, paramName, hasDefaultValue, defaultValue, isLeftover, isParams));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@@ -4,6 +4,7 @@ public sealed record ParamData(
|
|||||||
Type Type,
|
Type Type,
|
||||||
string Name,
|
string Name,
|
||||||
bool IsOptional,
|
bool IsOptional,
|
||||||
|
object? DefaultValue,
|
||||||
bool IsLeftover,
|
bool IsLeftover,
|
||||||
bool IsParams
|
bool IsParams
|
||||||
);
|
);
|
@@ -1,5 +1,6 @@
|
|||||||
#nullable disable warnings
|
#nullable disable warnings
|
||||||
using SixLabors.ImageSharp.PixelFormats;
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace NadekoBot;
|
namespace NadekoBot;
|
||||||
|
|
||||||
@@ -7,14 +8,14 @@ public sealed record SmartEmbedArrayElementText : SmartEmbedTextBase
|
|||||||
{
|
{
|
||||||
public string Color { get; init; } = string.Empty;
|
public string Color { get; init; } = string.Empty;
|
||||||
|
|
||||||
public SmartEmbedArrayElementText() : base()
|
public SmartEmbedArrayElementText()
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public SmartEmbedArrayElementText(IEmbed eb) : base(eb)
|
public SmartEmbedArrayElementText(IEmbed eb) : base(eb)
|
||||||
{
|
{
|
||||||
|
Color = eb.Color is { } c ? new Rgba32(c.R, c.G, c.B).ToHex() : string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override EmbedBuilder GetEmbedInternal()
|
protected override EmbedBuilder GetEmbedInternal()
|
||||||
@@ -63,6 +64,7 @@ public abstract record SmartEmbedTextBase : SmartText
|
|||||||
public SmartTextEmbedFooter Footer { get; init; }
|
public SmartTextEmbedFooter Footer { get; init; }
|
||||||
public SmartTextEmbedField[] Fields { get; init; }
|
public SmartTextEmbedField[] Fields { get; init; }
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
public bool IsValid
|
public bool IsValid
|
||||||
=> !string.IsNullOrWhiteSpace(Title)
|
=> !string.IsNullOrWhiteSpace(Title)
|
||||||
|| !string.IsNullOrWhiteSpace(Description)
|
|| !string.IsNullOrWhiteSpace(Description)
|
||||||
|
@@ -1,4 +1,6 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace NadekoBot;
|
namespace NadekoBot;
|
||||||
|
|
||||||
public sealed record SmartEmbedTextArray : SmartText
|
public sealed record SmartEmbedTextArray : SmartText
|
||||||
@@ -6,6 +8,7 @@ public sealed record SmartEmbedTextArray : SmartText
|
|||||||
public string Content { get; set; }
|
public string Content { get; set; }
|
||||||
public SmartEmbedArrayElementText[] Embeds { get; set; }
|
public SmartEmbedArrayElementText[] Embeds { get; set; }
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
public bool IsValid
|
public bool IsValid
|
||||||
=> Embeds?.All(x => x.IsValid) ?? false;
|
=> Embeds?.All(x => x.IsValid) ?? false;
|
||||||
|
|
||||||
|
@@ -1,16 +1,20 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace NadekoBot;
|
namespace NadekoBot;
|
||||||
|
|
||||||
public abstract record SmartText
|
public abstract record SmartText
|
||||||
{
|
{
|
||||||
|
[JsonIgnore]
|
||||||
public bool IsEmbed
|
public bool IsEmbed
|
||||||
=> this is SmartEmbedText;
|
=> this is SmartEmbedText;
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
public bool IsPlainText
|
public bool IsPlainText
|
||||||
=> this is SmartPlainText;
|
=> this is SmartPlainText;
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
public bool IsEmbedArray
|
public bool IsEmbedArray
|
||||||
=> this is SmartEmbedTextArray;
|
=> this is SmartEmbedTextArray;
|
||||||
|
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace NadekoBot;
|
namespace NadekoBot;
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ public class SmartTextEmbedAuthor
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
[JsonProperty("icon_url")]
|
[JsonProperty("icon_url")]
|
||||||
|
[JsonPropertyName("icon_url")]
|
||||||
public string IconUrl { get; set; }
|
public string IconUrl { get; set; }
|
||||||
|
|
||||||
public string Url { get; set; }
|
public string Url { get; set; }
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace NadekoBot;
|
namespace NadekoBot;
|
||||||
|
|
||||||
@@ -8,5 +9,6 @@ public class SmartTextEmbedFooter
|
|||||||
public string Text { get; set; }
|
public string Text { get; set; }
|
||||||
|
|
||||||
[JsonProperty("icon_url")]
|
[JsonProperty("icon_url")]
|
||||||
|
[JsonPropertyName("icon_url")]
|
||||||
public string IconUrl { get; set; }
|
public string IconUrl { get; set; }
|
||||||
}
|
}
|
@@ -46,9 +46,7 @@ public sealed class CommandOrExprTypeReader : NadekoTypeReader<CommandOrExprInfo
|
|||||||
|
|
||||||
public override async ValueTask<TypeReaderResult<CommandOrExprInfo>> ReadAsync(ICommandContext ctx, string input)
|
public override async ValueTask<TypeReaderResult<CommandOrExprInfo>> ReadAsync(ICommandContext ctx, string input)
|
||||||
{
|
{
|
||||||
input = input.ToUpperInvariant();
|
if (_exprs.ExpressionExists(ctx.Guild?.Id, input))
|
||||||
|
|
||||||
if (_exprs.ExpressionExists(ctx.Guild?.Id, input) || _exprs.ExpressionExists(null, input))
|
|
||||||
return TypeReaderResult.FromSuccess(new CommandOrExprInfo(input, CommandOrExprInfo.Type.Custom));
|
return TypeReaderResult.FromSuccess(new CommandOrExprInfo(input, CommandOrExprInfo.Type.Custom));
|
||||||
|
|
||||||
var cmd = await new CommandTypeReader(_commandHandler, _cmds).ReadAsync(ctx, input);
|
var cmd = await new CommandTypeReader(_commandHandler, _cmds).ReadAsync(ctx, input);
|
||||||
|
@@ -4,11 +4,60 @@ using LinqToDB.EntityFrameworkCore;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using NadekoBot.Db.Models;
|
using NadekoBot.Db.Models;
|
||||||
using NadekoBot.Services.Database;
|
using NadekoBot.Services.Database;
|
||||||
|
using System.Collections.Immutable;
|
||||||
|
|
||||||
namespace NadekoBot.Db;
|
namespace NadekoBot.Db;
|
||||||
|
|
||||||
public static class DiscordUserExtensions
|
public static class DiscordUserExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Adds the specified <paramref name="users"/> to the database. If a database user with placeholder name
|
||||||
|
/// and discriminator is present in <paramref name="users"/>, their name and discriminator get updated accordingly.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ctx">This database context.</param>
|
||||||
|
/// <param name="users">The users to add or update in the database.</param>
|
||||||
|
/// <returns>A tuple with the amount of new users added and old users updated.</returns>
|
||||||
|
public static async Task<(long UsersAdded, long UsersUpdated)> RefreshUsersAsync(this NadekoContext ctx, List<IUser> users)
|
||||||
|
{
|
||||||
|
var presentDbUsers = await ctx.DiscordUser
|
||||||
|
.Select(x => new { x.UserId, x.Username, x.Discriminator })
|
||||||
|
.Where(x => users.Select(y => y.Id).Contains(x.UserId))
|
||||||
|
.ToArrayAsyncEF();
|
||||||
|
|
||||||
|
var usersToAdd = users
|
||||||
|
.Where(x => !presentDbUsers.Select(x => x.UserId).Contains(x.Id))
|
||||||
|
.Select(x => new DiscordUser()
|
||||||
|
{
|
||||||
|
UserId = x.Id,
|
||||||
|
AvatarId = x.AvatarId,
|
||||||
|
Username = x.Username,
|
||||||
|
Discriminator = x.Discriminator
|
||||||
|
});
|
||||||
|
|
||||||
|
var added = (await ctx.BulkCopyAsync(usersToAdd)).RowsCopied;
|
||||||
|
var toUpdateUserIds = presentDbUsers
|
||||||
|
.Where(x => x.Username == "Unknown" && x.Discriminator == "????")
|
||||||
|
.Select(x => x.UserId)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
foreach (var user in users.Where(x => toUpdateUserIds.Contains(x.Id)))
|
||||||
|
{
|
||||||
|
await ctx.DiscordUser
|
||||||
|
.Where(x => x.UserId == user.Id)
|
||||||
|
.UpdateAsync(x => new DiscordUser()
|
||||||
|
{
|
||||||
|
Username = user.Username,
|
||||||
|
Discriminator = user.Discriminator,
|
||||||
|
|
||||||
|
// .award tends to set AvatarId and DateAdded to NULL, so account for that.
|
||||||
|
AvatarId = user.AvatarId,
|
||||||
|
DateAdded = x.DateAdded ?? DateTime.UtcNow
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (added, toUpdateUserIds.Length);
|
||||||
|
}
|
||||||
|
|
||||||
public static Task<DiscordUser> GetByUserIdAsync(
|
public static Task<DiscordUser> GetByUserIdAsync(
|
||||||
this IQueryable<DiscordUser> set,
|
this IQueryable<DiscordUser> set,
|
||||||
ulong userId)
|
ulong userId)
|
||||||
|
@@ -12,10 +12,4 @@ public static class NadekoExpressionExtensions
|
|||||||
|
|
||||||
public static IEnumerable<NadekoExpression> ForId(this DbSet<NadekoExpression> exprs, ulong id)
|
public static IEnumerable<NadekoExpression> ForId(this DbSet<NadekoExpression> exprs, ulong id)
|
||||||
=> exprs.AsNoTracking().AsQueryable().Where(x => x.GuildId == id).ToList();
|
=> exprs.AsNoTracking().AsQueryable().Where(x => x.GuildId == id).ToList();
|
||||||
|
|
||||||
public static NadekoExpression GetByGuildIdAndInput(
|
|
||||||
this DbSet<NadekoExpression> exprs,
|
|
||||||
ulong? guildId,
|
|
||||||
string input)
|
|
||||||
=> exprs.FirstOrDefault(x => x.GuildId == guildId && x.Trigger.ToUpper() == input);
|
|
||||||
}
|
}
|
@@ -28,5 +28,10 @@ public class DiscordUser : DbEntity
|
|||||||
=> UserId.GetHashCode();
|
=> UserId.GetHashCode();
|
||||||
|
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
=> Username + "#" + Discriminator;
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(Discriminator) || Discriminator == "0000")
|
||||||
|
return Username;
|
||||||
|
|
||||||
|
return Username + "#" + Discriminator;
|
||||||
|
}
|
||||||
}
|
}
|
@@ -19,25 +19,25 @@ public class WaifuInfo : DbEntity
|
|||||||
|
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
{
|
{
|
||||||
var claimer = "no one";
|
|
||||||
var status = string.Empty;
|
var status = string.Empty;
|
||||||
|
|
||||||
var waifuUsername = Waifu.Username.TrimTo(20);
|
var waifuUsername = Waifu.ToString().TrimTo(20);
|
||||||
var claimerUsername = Claimer?.Username.TrimTo(20);
|
var claimer = Claimer?.ToString().TrimTo(20)
|
||||||
|
?? "no one";
|
||||||
|
|
||||||
|
var affinity = Affinity?.ToString().TrimTo(20);
|
||||||
|
|
||||||
if (ClaimerId is not null)
|
|
||||||
claimer = $"{claimerUsername}#{Claimer.Discriminator}";
|
|
||||||
if (AffinityId is null)
|
if (AffinityId is null)
|
||||||
status = $"... but {waifuUsername}'s heart is empty";
|
status = $"... but {waifuUsername}'s heart is empty";
|
||||||
else if (AffinityId == ClaimerId)
|
else if (AffinityId == ClaimerId)
|
||||||
status = $"... and {waifuUsername} likes {claimerUsername} too <3";
|
status = $"... and {waifuUsername} likes {claimer} too <3";
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
status =
|
status =
|
||||||
$"... but {waifuUsername}'s heart belongs to {Affinity.Username.TrimTo(20)}#{Affinity.Discriminator}";
|
$"... but {waifuUsername}'s heart belongs to {affinity}";
|
||||||
}
|
}
|
||||||
|
|
||||||
return $"**{waifuUsername}#{Waifu.Discriminator}** - claimed by **{claimer}**\n\t{status}";
|
return $"**{waifuUsername}** - claimed by **{claimer}**\n\t{status}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -65,7 +65,10 @@ public partial class Administration
|
|||||||
_localization.SetGuildCulture(ctx.Guild, ci);
|
_localization.SetGuildCulture(ctx.Guild, ci);
|
||||||
}
|
}
|
||||||
|
|
||||||
await ReplyConfirmLocalizedAsync(strs.lang_set(Format.Bold(ci.ToString()), Format.Bold(ci.NativeName)));
|
var nativeName = ci.NativeName;
|
||||||
|
if (ci.Name == "ts-TS")
|
||||||
|
nativeName = _supportedLocales[ci.Name];
|
||||||
|
await ReplyConfirmLocalizedAsync(strs.lang_set(Format.Bold(ci.ToString()), Format.Bold(nativeName)));
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
|
@@ -19,6 +19,7 @@ public class MuteService : INService
|
|||||||
|
|
||||||
private static readonly OverwritePermissions _denyOverwrite = new(addReactions: PermValue.Deny,
|
private static readonly OverwritePermissions _denyOverwrite = new(addReactions: PermValue.Deny,
|
||||||
sendMessages: PermValue.Deny,
|
sendMessages: PermValue.Deny,
|
||||||
|
sendMessagesInThreads: PermValue.Deny,
|
||||||
attachFiles: PermValue.Deny);
|
attachFiles: PermValue.Deny);
|
||||||
|
|
||||||
public event Action<IGuildUser, IUser, MuteType, string> UserMuted = delegate { };
|
public event Action<IGuildUser, IUser, MuteType, string> UserMuted = delegate { };
|
||||||
@@ -356,24 +357,24 @@ public class MuteService : INService
|
|||||||
|
|
||||||
public async Task TimedBan(
|
public async Task TimedBan(
|
||||||
IGuild guild,
|
IGuild guild,
|
||||||
IUser user,
|
ulong userId,
|
||||||
TimeSpan after,
|
TimeSpan after,
|
||||||
string reason,
|
string reason,
|
||||||
int pruneDays)
|
int pruneDays)
|
||||||
{
|
{
|
||||||
await guild.AddBanAsync(user.Id, pruneDays, reason);
|
await guild.AddBanAsync(userId, pruneDays, reason);
|
||||||
await using (var uow = _db.GetDbContext())
|
await using (var uow = _db.GetDbContext())
|
||||||
{
|
{
|
||||||
var config = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.UnbanTimer));
|
var config = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.UnbanTimer));
|
||||||
config.UnbanTimer.Add(new()
|
config.UnbanTimer.Add(new()
|
||||||
{
|
{
|
||||||
UserId = user.Id,
|
UserId = userId,
|
||||||
UnbanAt = DateTime.UtcNow + after
|
UnbanAt = DateTime.UtcNow + after
|
||||||
}); // add teh unmute timer to the database
|
}); // add teh unmute timer to the database
|
||||||
uow.SaveChanges();
|
await uow.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
StartUn_Timer(guild.Id, user.Id, after, TimerType.Ban); // start the timer
|
StartUn_Timer(guild.Id, userId, after, TimerType.Ban); // start the timer
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task TimedRole(
|
public async Task TimedRole(
|
||||||
|
@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration;
|
|||||||
public sealed class DoAsUserMessage : IUserMessage
|
public sealed class DoAsUserMessage : IUserMessage
|
||||||
{
|
{
|
||||||
private readonly string _message;
|
private readonly string _message;
|
||||||
private IUserMessage _msg;
|
private readonly IUserMessage _msg;
|
||||||
private readonly IUser _user;
|
private readonly IUser _user;
|
||||||
|
|
||||||
public DoAsUserMessage(SocketUserMessage msg, IUser user, string message)
|
public DoAsUserMessage(SocketUserMessage msg, IUser user, string message)
|
||||||
@@ -49,6 +49,13 @@ public sealed class DoAsUserMessage : IUserMessage
|
|||||||
return _msg.RemoveAllReactionsForEmoteAsync(emote, options);
|
return _msg.RemoveAllReactionsForEmoteAsync(emote, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(
|
||||||
|
IEmote emoji,
|
||||||
|
int limit,
|
||||||
|
RequestOptions? options = null,
|
||||||
|
ReactionType type = ReactionType.Normal)
|
||||||
|
=> _msg.GetReactionUsersAsync(emoji, limit, options, type);
|
||||||
|
|
||||||
public IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IEmote emoji, int limit,
|
public IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IEmote emoji, int limit,
|
||||||
RequestOptions? options = null)
|
RequestOptions? options = null)
|
||||||
{
|
{
|
||||||
@@ -78,6 +85,7 @@ public sealed class DoAsUserMessage : IUserMessage
|
|||||||
public IMessageChannel Channel => _msg.Channel;
|
public IMessageChannel Channel => _msg.Channel;
|
||||||
|
|
||||||
public IUser Author => _user;
|
public IUser Author => _user;
|
||||||
|
public IThreadChannel Thread => _msg.Thread;
|
||||||
|
|
||||||
public IReadOnlyCollection<IAttachment> Attachments => _msg.Attachments;
|
public IReadOnlyCollection<IAttachment> Attachments => _msg.Attachments;
|
||||||
|
|
||||||
@@ -106,6 +114,7 @@ public sealed class DoAsUserMessage : IUserMessage
|
|||||||
public MessageFlags? Flags => _msg.Flags;
|
public MessageFlags? Flags => _msg.Flags;
|
||||||
|
|
||||||
public IMessageInteraction Interaction => _msg.Interaction;
|
public IMessageInteraction Interaction => _msg.Interaction;
|
||||||
|
public MessageRoleSubscriptionData RoleSubscriptionData => _msg.RoleSubscriptionData;
|
||||||
|
|
||||||
public Task ModifyAsync(Action<MessageProperties> func, RequestOptions? options = null)
|
public Task ModifyAsync(Action<MessageProperties> func, RequestOptions? options = null)
|
||||||
{
|
{
|
||||||
@@ -134,5 +143,8 @@ public sealed class DoAsUserMessage : IUserMessage
|
|||||||
return _msg.Resolve(userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);
|
return _msg.Resolve(userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public MessageResolvedData ResolvedData => _msg.ResolvedData;
|
||||||
|
|
||||||
public IUserMessage ReferencedMessage => _msg.ReferencedMessage;
|
public IUserMessage ReferencedMessage => _msg.ReferencedMessage;
|
||||||
|
public IMessageInteractionMetadata InteractionMetadata { get; }
|
||||||
}
|
}
|
@@ -1,5 +1,6 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using Nadeko.Medusa;
|
using Nadeko.Medusa;
|
||||||
|
using NadekoBot.Db;
|
||||||
using NadekoBot.Modules.Administration.Services;
|
using NadekoBot.Modules.Administration.Services;
|
||||||
using NadekoBot.Services.Database.Models;
|
using NadekoBot.Services.Database.Models;
|
||||||
|
|
||||||
@@ -22,19 +23,53 @@ public partial class Administration
|
|||||||
private readonly IBotStrings _strings;
|
private readonly IBotStrings _strings;
|
||||||
private readonly IMedusaLoaderService _medusaLoader;
|
private readonly IMedusaLoaderService _medusaLoader;
|
||||||
private readonly ICoordinator _coord;
|
private readonly ICoordinator _coord;
|
||||||
|
private readonly DbService _db;
|
||||||
|
|
||||||
public SelfCommands(
|
public SelfCommands(
|
||||||
DiscordSocketClient client,
|
DiscordSocketClient client,
|
||||||
|
DbService db,
|
||||||
IBotStrings strings,
|
IBotStrings strings,
|
||||||
ICoordinator coord,
|
ICoordinator coord,
|
||||||
IMedusaLoaderService medusaLoader)
|
IMedusaLoaderService medusaLoader)
|
||||||
{
|
{
|
||||||
_client = client;
|
_client = client;
|
||||||
|
_db = db;
|
||||||
_strings = strings;
|
_strings = strings;
|
||||||
_coord = coord;
|
_coord = coord;
|
||||||
_medusaLoader = medusaLoader;
|
_medusaLoader = medusaLoader;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[RequireContext(ContextType.Guild)]
|
||||||
|
[OwnerOnly]
|
||||||
|
public Task CacheUsers()
|
||||||
|
=> CacheUsers(ctx.Guild);
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[OwnerOnly]
|
||||||
|
public async Task CacheUsers(IGuild guild)
|
||||||
|
{
|
||||||
|
var downloadUsersTask = guild.DownloadUsersAsync();
|
||||||
|
var message = await ReplyPendingLocalizedAsync(strs.cache_users_pending);
|
||||||
|
using var dbContext = _db.GetDbContext();
|
||||||
|
|
||||||
|
await downloadUsersTask;
|
||||||
|
|
||||||
|
var users = (await guild.GetUsersAsync(CacheMode.CacheOnly))
|
||||||
|
.Cast<IUser>()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var (added, updated) = await dbContext.RefreshUsersAsync(users);
|
||||||
|
|
||||||
|
await message.ModifyAsync(x =>
|
||||||
|
x.Embed = _eb.Create()
|
||||||
|
.WithDescription(GetText(strs.cache_users_done(added, updated)))
|
||||||
|
.WithOkColor()
|
||||||
|
.Build()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
[OwnerOnly]
|
[OwnerOnly]
|
||||||
public async Task DoAs(IUser user, [Leftover] string message)
|
public async Task DoAs(IUser user, [Leftover] string message)
|
||||||
@@ -467,6 +502,16 @@ public partial class Administration
|
|||||||
await ReplyConfirmLocalizedAsync(strs.set_avatar);
|
await ReplyConfirmLocalizedAsync(strs.set_avatar);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[OwnerOnly]
|
||||||
|
public async Task SetBanner([Leftover] string img = null)
|
||||||
|
{
|
||||||
|
var success = await _service.SetBanner(img);
|
||||||
|
|
||||||
|
if (success)
|
||||||
|
await ReplyConfirmLocalizedAsync(strs.set_banner);
|
||||||
|
}
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
[OwnerOnly]
|
[OwnerOnly]
|
||||||
public async Task SetGame(ActivityType type, [Leftover] string game = null)
|
public async Task SetGame(ActivityType type, [Leftover] string game = null)
|
||||||
|
@@ -3,7 +3,6 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using NadekoBot.Common.ModuleBehaviors;
|
using NadekoBot.Common.ModuleBehaviors;
|
||||||
using NadekoBot.Services.Database.Models;
|
using NadekoBot.Services.Database.Models;
|
||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using Nadeko.Common;
|
|
||||||
|
|
||||||
namespace NadekoBot.Modules.Administration.Services;
|
namespace NadekoBot.Modules.Administration.Services;
|
||||||
|
|
||||||
@@ -321,6 +320,40 @@ public sealed class SelfService : IExecNoCommand, IReadyExecutor, INService
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> SetBanner(string img)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(img))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Uri.IsWellFormedUriString(img, UriKind.Absolute))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var uri = new Uri(img);
|
||||||
|
|
||||||
|
using var http = _httpFactory.CreateClient();
|
||||||
|
using var sr = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
|
||||||
|
|
||||||
|
if (!sr.IsImage())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sr.GetContentLength() > 8.Megabytes().Bytes)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await using var imageStream = await sr.Content.ReadAsStreamAsync();
|
||||||
|
|
||||||
|
await _client.CurrentUser.ModifyAsync(x => x.Banner = new Image(imageStream));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public void ClearStartupCommands()
|
public void ClearStartupCommands()
|
||||||
{
|
{
|
||||||
using var uow = _db.GetDbContext();
|
using var uow = _db.GetDbContext();
|
||||||
|
@@ -9,9 +9,9 @@ using NadekoBot.Services.Database.Models;
|
|||||||
namespace NadekoBot.Modules.Administration;
|
namespace NadekoBot.Modules.Administration;
|
||||||
|
|
||||||
public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
||||||
#if !GLOBAL_NADEKO
|
#if !GLOBAL_NADEKO
|
||||||
, INService // don't load this service on global nadeko
|
, INService // don't load this service on global nadeko
|
||||||
#endif
|
#endif
|
||||||
{
|
{
|
||||||
public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }
|
public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }
|
||||||
|
|
||||||
@@ -54,10 +54,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
{
|
{
|
||||||
var guildIds = client.Guilds.Select(x => x.Id).ToList();
|
var guildIds = client.Guilds.Select(x => x.Id).ToList();
|
||||||
var configs = uow.LogSettings.AsQueryable()
|
var configs = uow.LogSettings.AsQueryable()
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(x => guildIds.Contains(x.GuildId))
|
.Where(x => guildIds.Contains(x.GuildId))
|
||||||
.Include(ls => ls.LogIgnores)
|
.Include(ls => ls.LogIgnores)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
GuildLogSettings = configs.ToDictionary(ls => ls.GuildId).ToConcurrent();
|
GuildLogSettings = configs.ToDictionary(ls => ls.GuildId).ToConcurrent();
|
||||||
}
|
}
|
||||||
@@ -73,6 +73,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated;
|
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated;
|
||||||
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS;
|
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS;
|
||||||
_client.GuildMemberUpdated += _client_GuildUserUpdated;
|
_client.GuildMemberUpdated += _client_GuildUserUpdated;
|
||||||
|
_client.PresenceUpdated += _client_PresenceUpdated;
|
||||||
_client.UserUpdated += _client_UserUpdated;
|
_client.UserUpdated += _client_UserUpdated;
|
||||||
_client.ChannelCreated += _client_ChannelCreated;
|
_client.ChannelCreated += _client_ChannelCreated;
|
||||||
_client.ChannelDestroyed += _client_ChannelDestroyed;
|
_client.ChannelDestroyed += _client_ChannelDestroyed;
|
||||||
@@ -90,15 +91,71 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
_punishService.OnUserWarned += PunishServiceOnOnUserWarned;
|
_punishService.OnUserWarned += PunishServiceOnOnUserWarned;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task _client_PresenceUpdated(SocketUser user, SocketPresence? before, SocketPresence? after)
|
||||||
|
{
|
||||||
|
if (user is not SocketGuildUser gu)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (!GuildLogSettings.TryGetValue(gu.Guild.Id, out var logSetting)
|
||||||
|
|| before is null
|
||||||
|
|| after is null
|
||||||
|
|| logSetting.LogIgnores.Any(ilc => ilc.LogItemId == gu.Id && ilc.ItemType == IgnoredItemType.User))
|
||||||
|
return;
|
||||||
|
|
||||||
|
ITextChannel? logChannel;
|
||||||
|
|
||||||
|
if (!user.IsBot
|
||||||
|
&& logSetting.LogUserPresenceId is not null
|
||||||
|
&& (logChannel =
|
||||||
|
await TryGetLogChannel(gu.Guild, logSetting, LogType.UserPresence)) is not null)
|
||||||
|
{
|
||||||
|
if (before.Status != after.Status)
|
||||||
|
{
|
||||||
|
var str = "🎭"
|
||||||
|
+ Format.Code(PrettyCurrentTime(gu.Guild))
|
||||||
|
+ GetText(logChannel.Guild,
|
||||||
|
strs.user_status_change("👤" + Format.Bold(gu.Username),
|
||||||
|
Format.Bold(after.Status.ToString())));
|
||||||
|
PresenceUpdates.AddOrUpdate(logChannel,
|
||||||
|
new List<string>
|
||||||
|
{
|
||||||
|
str
|
||||||
|
},
|
||||||
|
(_, list) =>
|
||||||
|
{
|
||||||
|
list.Add(str);
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else if (before.Activities.FirstOrDefault()?.Name != after.Activities.FirstOrDefault()?.Name)
|
||||||
|
{
|
||||||
|
var str =
|
||||||
|
$"👾`{PrettyCurrentTime(gu.Guild)}`👤__**{gu.Username}**__ is now playing **{after.Activities.FirstOrDefault()?.Name ?? "-"}**.";
|
||||||
|
PresenceUpdates.AddOrUpdate(logChannel,
|
||||||
|
new List<string>
|
||||||
|
{
|
||||||
|
str
|
||||||
|
},
|
||||||
|
(_, list) =>
|
||||||
|
{
|
||||||
|
list.Add(str);
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Task _client_ThreadDeleted(Cacheable<SocketThreadChannel, ulong> sch)
|
private Task _client_ThreadDeleted(Cacheable<SocketThreadChannel, ulong> sch)
|
||||||
{
|
{
|
||||||
_ = Task.Run(async () =>
|
_ = Task.Run(async () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (sch.HasValue || sch.Value is not IGuildChannel ch)
|
if (!sch.HasValue)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
var ch = sch.Value;
|
||||||
|
|
||||||
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|
||||||
|| logSetting.ThreadDeletedId is null)
|
|| logSetting.ThreadDeletedId is null)
|
||||||
return;
|
return;
|
||||||
@@ -111,7 +168,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
|
|
||||||
await logChannel.EmbedAsync(_eb.Create()
|
await logChannel.EmbedAsync(_eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("🆕 " + title)
|
.WithTitle("🗑 " + title)
|
||||||
.WithDescription($"{ch.Name} | {ch.Id}")
|
.WithDescription($"{ch.Name} | {ch.Id}")
|
||||||
.WithFooter(CurrentTime(ch.Guild)));
|
.WithFooter(CurrentTime(ch.Guild)));
|
||||||
}
|
}
|
||||||
@@ -123,15 +180,12 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task _client_ThreadCreated(SocketThreadChannel sch)
|
private Task _client_ThreadCreated(SocketThreadChannel ch)
|
||||||
{
|
{
|
||||||
_ = Task.Run(async () =>
|
_ = Task.Run(async () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (sch.Guild is not IGuildChannel ch)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
|
||||||
|| logSetting.ThreadCreatedId is null)
|
|| logSetting.ThreadCreatedId is null)
|
||||||
return;
|
return;
|
||||||
@@ -177,22 +231,24 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
var keys = PresenceUpdates.Keys.ToList();
|
var keys = PresenceUpdates.Keys.ToList();
|
||||||
|
|
||||||
await keys.Select(key =>
|
await keys.Select(key =>
|
||||||
{
|
{
|
||||||
if (!((SocketGuild)key.Guild).CurrentUser.GetPermissions(key).SendMessages)
|
if (!((SocketGuild)key.Guild).CurrentUser.GetPermissions(key).SendMessages)
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
if (PresenceUpdates.TryRemove(key, out var msgs))
|
if (PresenceUpdates.TryRemove(key, out var msgs))
|
||||||
{
|
{
|
||||||
var title = GetText(key.Guild, strs.presence_updates);
|
var title = GetText(key.Guild, strs.presence_updates);
|
||||||
var desc = string.Join(Environment.NewLine, msgs);
|
var desc = string.Join(Environment.NewLine, msgs);
|
||||||
return key.SendConfirmAsync(_eb, title, desc.TrimTo(2048)!);
|
return key.SendConfirmAsync(_eb, title, desc.TrimTo(2048)!);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
})
|
})
|
||||||
.WhenAll();
|
.WhenAll();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
}
|
}
|
||||||
catch { }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -255,13 +311,13 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
logSetting.UserLeftId = logSetting.UserBannedId = logSetting.UserUnbannedId = logSetting.UserUpdatedId =
|
logSetting.UserLeftId = logSetting.UserBannedId = logSetting.UserUnbannedId = logSetting.UserUpdatedId =
|
||||||
logSetting.ChannelCreatedId = logSetting.ChannelDestroyedId = logSetting.ChannelUpdatedId =
|
logSetting.ChannelCreatedId = logSetting.ChannelDestroyedId = logSetting.ChannelUpdatedId =
|
||||||
logSetting.LogUserPresenceId = logSetting.LogVoicePresenceId = logSetting.UserMutedId =
|
logSetting.LogUserPresenceId = logSetting.LogVoicePresenceId = logSetting.UserMutedId =
|
||||||
logSetting.LogVoicePresenceTTSId = value ? channelId : null;
|
logSetting.LogVoicePresenceTTSId = logSetting.ThreadCreatedId = logSetting.ThreadDeletedId
|
||||||
|
= logSetting.LogWarnsId = value ? channelId : null;
|
||||||
await uow.SaveChangesAsync();
|
await uow.SaveChangesAsync();
|
||||||
GuildLogSettings.AddOrUpdate(guildId, _ => logSetting, (_, _) => logSetting);
|
GuildLogSettings.AddOrUpdate(guildId, _ => logSetting, (_, _) => logSetting);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private async Task PunishServiceOnOnUserWarned(Warning arg)
|
private async Task PunishServiceOnOnUserWarned(Warning arg)
|
||||||
{
|
{
|
||||||
if (!GuildLogSettings.TryGetValue(arg.GuildId, out var logSetting) || logSetting.LogWarnsId is null)
|
if (!GuildLogSettings.TryGetValue(arg.GuildId, out var logSetting) || logSetting.LogWarnsId is null)
|
||||||
@@ -274,12 +330,12 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle($"⚠️ User Warned")
|
.WithTitle($"⚠️ User Warned")
|
||||||
.WithDescription($"<@{arg.UserId}> | {arg.UserId}")
|
.WithDescription($"<@{arg.UserId}> | {arg.UserId}")
|
||||||
.AddField("Mod", arg.Moderator)
|
.AddField("Mod", arg.Moderator)
|
||||||
.AddField("Reason", string.IsNullOrWhiteSpace(arg.Reason) ? "-" : arg.Reason, true)
|
.AddField("Reason", string.IsNullOrWhiteSpace(arg.Reason) ? "-" : arg.Reason, true)
|
||||||
.WithFooter(CurrentTime(g));
|
.WithFooter(CurrentTime(g));
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -295,7 +351,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
|
|
||||||
var g = after.Guild;
|
var g = after.Guild;
|
||||||
|
|
||||||
if (!GuildLogSettings.TryGetValue(g.Id, out var logSetting) || logSetting.UserUpdatedId is null)
|
if (!GuildLogSettings.TryGetValue(g.Id, out var logSetting) || logSetting.UserUpdatedId is null || logSetting.LogIgnores.Any(ilc => ilc.LogItemId == after.Id && ilc.ItemType == IgnoredItemType.User))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
ITextChannel? logChannel;
|
ITextChannel? logChannel;
|
||||||
@@ -307,18 +363,18 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
if (before.Username != after.Username)
|
if (before.Username != after.Username)
|
||||||
{
|
{
|
||||||
embed.WithTitle("👥 " + GetText(g, strs.username_changed))
|
embed.WithTitle("👥 " + GetText(g, strs.username_changed))
|
||||||
.WithDescription($"{before.Username}#{before.Discriminator} | {before.Id}")
|
.WithDescription($"{before.Username} | {before.Id}")
|
||||||
.AddField("Old Name", $"{before.Username}", true)
|
.AddField("Old Name", $"{before.Username}", true)
|
||||||
.AddField("New Name", $"{after.Username}", true)
|
.AddField("New Name", $"{after.Username}", true)
|
||||||
.WithFooter(CurrentTime(g))
|
.WithFooter(CurrentTime(g))
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
}
|
}
|
||||||
else if (before.AvatarId != after.AvatarId)
|
else if (before.AvatarId != after.AvatarId)
|
||||||
{
|
{
|
||||||
embed.WithTitle("👥" + GetText(g, strs.avatar_changed))
|
embed.WithTitle("👥" + GetText(g, strs.avatar_changed))
|
||||||
.WithDescription($"{before.Username}#{before.Discriminator} | {before.Id}")
|
.WithDescription($"{before.Username}#{before.Discriminator} | {before.Id}")
|
||||||
.WithFooter(CurrentTime(g))
|
.WithFooter(CurrentTime(g))
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
|
|
||||||
var bav = before.RealAvatarUrl();
|
var bav = before.RealAvatarUrl();
|
||||||
if (bav.IsAbsoluteUri)
|
if (bav.IsAbsoluteUri)
|
||||||
@@ -400,6 +456,12 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
case LogType.UserWarned:
|
case LogType.UserWarned:
|
||||||
channelId = logSetting.LogWarnsId = logSetting.LogWarnsId is null ? cid : default;
|
channelId = logSetting.LogWarnsId = logSetting.LogWarnsId is null ? cid : default;
|
||||||
break;
|
break;
|
||||||
|
case LogType.ThreadDeleted:
|
||||||
|
channelId = logSetting.ThreadDeletedId = logSetting.ThreadDeletedId is null ? cid : default;
|
||||||
|
break;
|
||||||
|
case LogType.ThreadCreated:
|
||||||
|
channelId = logSetting.ThreadCreatedId = logSetting.ThreadCreatedId is null ? cid : default;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
uow.SaveChanges();
|
uow.SaveChanges();
|
||||||
@@ -482,10 +544,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
}
|
}
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithAuthor(mutes)
|
.WithAuthor(mutes)
|
||||||
.WithTitle($"{usr.Username}#{usr.Discriminator} | {usr.Id}")
|
.WithTitle($"{usr.Username}#{usr.Discriminator} | {usr.Id}")
|
||||||
.WithFooter(CurrentTime(usr.Guild))
|
.WithFooter(CurrentTime(usr.Guild))
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -529,10 +591,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
}
|
}
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithAuthor(mutes)
|
.WithAuthor(mutes)
|
||||||
.WithTitle($"{usr.Username}#{usr.Discriminator} | {usr.Id}")
|
.WithTitle($"{usr.Username}#{usr.Discriminator} | {usr.Id}")
|
||||||
.WithFooter($"{CurrentTime(usr.Guild)}")
|
.WithFooter($"{CurrentTime(usr.Guild)}")
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(reason))
|
if (!string.IsNullOrWhiteSpace(reason))
|
||||||
embed.WithDescription(reason);
|
embed.WithDescription(reason);
|
||||||
@@ -583,11 +645,11 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
}
|
}
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithAuthor($"🛡 Anti-{protection}")
|
.WithAuthor($"🛡 Anti-{protection}")
|
||||||
.WithTitle(GetText(logChannel.Guild, strs.users) + " " + punishment)
|
.WithTitle(GetText(logChannel.Guild, strs.users) + " " + punishment)
|
||||||
.WithDescription(string.Join("\n", users.Select(u => u.ToString())))
|
.WithDescription(string.Join("\n", users.Select(u => u.ToString())))
|
||||||
.WithFooter(CurrentTime(logChannel.Guild))
|
.WithFooter(CurrentTime(logChannel.Guild))
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -636,16 +698,16 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
&& (logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)) is not null)
|
&& (logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)) is not null)
|
||||||
{
|
{
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithFooter(CurrentTime(before.Guild))
|
.WithFooter(CurrentTime(before.Guild))
|
||||||
.WithTitle($"{before.Username}#{before.Discriminator} | {before.Id}");
|
.WithTitle($"{before.Username}#{before.Discriminator} | {before.Id}");
|
||||||
if (before.Nickname != after.Nickname)
|
if (before.Nickname != after.Nickname)
|
||||||
{
|
{
|
||||||
embed.WithAuthor("👥 " + GetText(logChannel.Guild, strs.nick_change))
|
embed.WithAuthor("👥 " + GetText(logChannel.Guild, strs.nick_change))
|
||||||
.AddField(GetText(logChannel.Guild, strs.old_nick),
|
.AddField(GetText(logChannel.Guild, strs.old_nick),
|
||||||
$"{before.Nickname}#{before.Discriminator}")
|
$"{before.Nickname}#{before.Discriminator}")
|
||||||
.AddField(GetText(logChannel.Guild, strs.new_nick),
|
.AddField(GetText(logChannel.Guild, strs.new_nick),
|
||||||
$"{after.Nickname}#{after.Discriminator}");
|
$"{after.Nickname}#{after.Discriminator}");
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -655,7 +717,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
{
|
{
|
||||||
var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => r.Name);
|
var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => r.Name);
|
||||||
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_add))
|
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_add))
|
||||||
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
|
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -663,59 +725,19 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
{
|
{
|
||||||
await Task.Delay(1000);
|
await Task.Delay(1000);
|
||||||
var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r) && !IsRoleDeleted(r.Id))
|
var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r) && !IsRoleDeleted(r.Id))
|
||||||
.Select(r => r.Name)
|
.Select(r => r.Name)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
if (diffRoles.Any())
|
if (diffRoles.Any())
|
||||||
{
|
{
|
||||||
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_rem))
|
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_rem))
|
||||||
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
|
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!before.IsBot
|
|
||||||
&& logSetting.LogUserPresenceId is not null
|
|
||||||
&& (logChannel =
|
|
||||||
await TryGetLogChannel(before.Guild, logSetting, LogType.UserPresence)) is not null)
|
|
||||||
{
|
|
||||||
if (before.Status != after.Status)
|
|
||||||
{
|
|
||||||
var str = "🎭"
|
|
||||||
+ Format.Code(PrettyCurrentTime(after.Guild))
|
|
||||||
+ GetText(logChannel.Guild,
|
|
||||||
strs.user_status_change("👤" + Format.Bold(after.Username),
|
|
||||||
Format.Bold(after.Status.ToString())));
|
|
||||||
PresenceUpdates.AddOrUpdate(logChannel,
|
|
||||||
new List<string>
|
|
||||||
{
|
|
||||||
str
|
|
||||||
},
|
|
||||||
(_, list) =>
|
|
||||||
{
|
|
||||||
list.Add(str);
|
|
||||||
return list;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else if (before.Activities.FirstOrDefault()?.Name != after.Activities.FirstOrDefault()?.Name)
|
|
||||||
{
|
|
||||||
var str =
|
|
||||||
$"👾`{PrettyCurrentTime(after.Guild)}`👤__**{after.Username}**__ is now playing **{after.Activities.FirstOrDefault()?.Name ?? "-"}**.";
|
|
||||||
PresenceUpdates.AddOrUpdate(logChannel,
|
|
||||||
new List<string>
|
|
||||||
{
|
|
||||||
str
|
|
||||||
},
|
|
||||||
(_, list) =>
|
|
||||||
{
|
|
||||||
list.Add(str);
|
|
||||||
return list;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -754,15 +776,15 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
if (before.Name != after.Name)
|
if (before.Name != after.Name)
|
||||||
{
|
{
|
||||||
embed.WithTitle("ℹ️ " + GetText(logChannel.Guild, strs.ch_name_change))
|
embed.WithTitle("ℹ️ " + GetText(logChannel.Guild, strs.ch_name_change))
|
||||||
.WithDescription($"{after} | {after.Id}")
|
.WithDescription($"{after} | {after.Id}")
|
||||||
.AddField(GetText(logChannel.Guild, strs.ch_old_name), before.Name);
|
.AddField(GetText(logChannel.Guild, strs.ch_old_name), before.Name);
|
||||||
}
|
}
|
||||||
else if (beforeTextChannel?.Topic != afterTextChannel?.Topic)
|
else if (beforeTextChannel?.Topic != afterTextChannel?.Topic)
|
||||||
{
|
{
|
||||||
embed.WithTitle("ℹ️ " + GetText(logChannel.Guild, strs.ch_topic_change))
|
embed.WithTitle("ℹ️ " + GetText(logChannel.Guild, strs.ch_topic_change))
|
||||||
.WithDescription($"{after} | {after.Id}")
|
.WithDescription($"{after} | {after.Id}")
|
||||||
.AddField(GetText(logChannel.Guild, strs.old_topic), beforeTextChannel?.Topic ?? "-")
|
.AddField(GetText(logChannel.Guild, strs.old_topic), beforeTextChannel?.Topic ?? "-")
|
||||||
.AddField(GetText(logChannel.Guild, strs.new_topic), afterTextChannel?.Topic ?? "-");
|
.AddField(GetText(logChannel.Guild, strs.new_topic), afterTextChannel?.Topic ?? "-");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
return;
|
return;
|
||||||
@@ -803,10 +825,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
title = GetText(logChannel.Guild, strs.text_chan_destroyed);
|
title = GetText(logChannel.Guild, strs.text_chan_destroyed);
|
||||||
|
|
||||||
await logChannel.EmbedAsync(_eb.Create()
|
await logChannel.EmbedAsync(_eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("🆕 " + title)
|
.WithTitle("🆕 " + title)
|
||||||
.WithDescription($"{ch.Name} | {ch.Id}")
|
.WithDescription($"{ch.Name} | {ch.Id}")
|
||||||
.WithFooter(CurrentTime(ch.Guild)));
|
.WithFooter(CurrentTime(ch.Guild)));
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -839,10 +861,10 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
title = GetText(logChannel.Guild, strs.text_chan_created);
|
title = GetText(logChannel.Guild, strs.text_chan_created);
|
||||||
|
|
||||||
await logChannel.EmbedAsync(_eb.Create()
|
await logChannel.EmbedAsync(_eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("🆕 " + title)
|
.WithTitle("🆕 " + title)
|
||||||
.WithDescription($"{ch.Name} | {ch.Id}")
|
.WithDescription($"{ch.Name} | {ch.Id}")
|
||||||
.WithFooter(CurrentTime(ch.Guild)));
|
.WithFooter(CurrentTime(ch.Guild)));
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
@@ -883,7 +905,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
str = "🎙"
|
str = "🎙"
|
||||||
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
||||||
+ GetText(logChannel.Guild,
|
+ GetText(logChannel.Guild,
|
||||||
strs.user_vmoved("👤" + Format.Bold(usr.Username + "#" + usr.Discriminator),
|
strs.user_vmoved("👤" + Format.Bold(usr.Username),
|
||||||
Format.Bold(beforeVch?.Name ?? ""),
|
Format.Bold(beforeVch?.Name ?? ""),
|
||||||
Format.Bold(afterVch?.Name ?? "")));
|
Format.Bold(afterVch?.Name ?? "")));
|
||||||
}
|
}
|
||||||
@@ -892,7 +914,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
str = "🎙"
|
str = "🎙"
|
||||||
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
||||||
+ GetText(logChannel.Guild,
|
+ GetText(logChannel.Guild,
|
||||||
strs.user_vjoined("👤" + Format.Bold(usr.Username + "#" + usr.Discriminator),
|
strs.user_vjoined("👤" + Format.Bold(usr.Username),
|
||||||
Format.Bold(afterVch?.Name ?? "")));
|
Format.Bold(afterVch?.Name ?? "")));
|
||||||
}
|
}
|
||||||
else if (afterVch is null)
|
else if (afterVch is null)
|
||||||
@@ -900,7 +922,7 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
str = "🎙"
|
str = "🎙"
|
||||||
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
+ Format.Code(PrettyCurrentTime(usr.Guild))
|
||||||
+ GetText(logChannel.Guild,
|
+ GetText(logChannel.Guild,
|
||||||
strs.user_vleft("👤" + Format.Bold(usr.Username + "#" + usr.Discriminator),
|
strs.user_vleft("👤" + Format.Bold(usr.Username),
|
||||||
Format.Bold(beforeVch.Name ?? "")));
|
Format.Bold(beforeVch.Name ?? "")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -942,11 +964,11 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserLeft)) is null)
|
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserLeft)) is null)
|
||||||
return;
|
return;
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("❌ " + GetText(logChannel.Guild, strs.user_left))
|
.WithTitle("❌ " + GetText(logChannel.Guild, strs.user_left))
|
||||||
.WithDescription(usr.ToString())
|
.WithDescription(usr.ToString())
|
||||||
.AddField("Id", usr.Id.ToString())
|
.AddField("Id", usr.Id.ToString())
|
||||||
.WithFooter(CurrentTime(guild));
|
.WithFooter(CurrentTime(guild));
|
||||||
|
|
||||||
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
||||||
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
||||||
@@ -975,17 +997,17 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("✅ " + GetText(logChannel.Guild, strs.user_joined))
|
.WithTitle("✅ " + GetText(logChannel.Guild, strs.user_joined))
|
||||||
.WithDescription($"{usr.Mention} `{usr}`")
|
.WithDescription($"{usr.Mention} `{usr}`")
|
||||||
.AddField("Id", usr.Id.ToString())
|
.AddField("Id", usr.Id.ToString())
|
||||||
.AddField(GetText(logChannel.Guild, strs.joined_server),
|
.AddField(GetText(logChannel.Guild, strs.joined_server),
|
||||||
$"{usr.JoinedAt?.ToString("dd.MM.yyyy HH:mm") ?? "?"}",
|
$"{usr.JoinedAt?.ToString("dd.MM.yyyy HH:mm") ?? "?"}",
|
||||||
true)
|
true)
|
||||||
.AddField(GetText(logChannel.Guild, strs.joined_discord),
|
.AddField(GetText(logChannel.Guild, strs.joined_discord),
|
||||||
$"{usr.CreatedAt:dd.MM.yyyy HH:mm}",
|
$"{usr.CreatedAt:dd.MM.yyyy HH:mm}",
|
||||||
true)
|
true)
|
||||||
.WithFooter(CurrentTime(usr.Guild));
|
.WithFooter(CurrentTime(usr.Guild));
|
||||||
|
|
||||||
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
||||||
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
||||||
@@ -1016,11 +1038,11 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)) is null)
|
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)) is null)
|
||||||
return;
|
return;
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("♻️ " + GetText(logChannel.Guild, strs.user_unbanned))
|
.WithTitle("♻️ " + GetText(logChannel.Guild, strs.user_unbanned))
|
||||||
.WithDescription(usr.ToString()!)
|
.WithDescription(usr.ToString()!)
|
||||||
.AddField("Id", usr.Id.ToString())
|
.AddField("Id", usr.Id.ToString())
|
||||||
.WithFooter(CurrentTime(guild));
|
.WithFooter(CurrentTime(guild));
|
||||||
|
|
||||||
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
|
||||||
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
embed.WithThumbnailUrl(usr.GetAvatarUrl());
|
||||||
@@ -1060,16 +1082,15 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("🚫 " + GetText(logChannel.Guild, strs.user_banned))
|
.WithTitle("🚫 " + GetText(logChannel.Guild, strs.user_banned))
|
||||||
.WithDescription(usr.ToString()!)
|
.WithDescription(usr.ToString()!)
|
||||||
.AddField("Id", usr.Id.ToString())
|
.AddField("Id", usr.Id.ToString())
|
||||||
.AddField("Reason", string.IsNullOrWhiteSpace(reason) ? "-" : reason)
|
.AddField("Reason", string.IsNullOrWhiteSpace(reason) ? "-" : reason)
|
||||||
.WithFooter(CurrentTime(guild));
|
.WithFooter(CurrentTime(guild));
|
||||||
|
|
||||||
var avatarUrl = usr.GetAvatarUrl();
|
var avatarUrl = usr.GetAvatarUrl();
|
||||||
|
|
||||||
@@ -1115,14 +1136,14 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
|
|
||||||
var resolvedMessage = msg.Resolve(TagHandling.FullName);
|
var resolvedMessage = msg.Resolve(TagHandling.FullName);
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("🗑 "
|
.WithTitle("🗑 "
|
||||||
+ GetText(logChannel.Guild, strs.msg_del(((ITextChannel)msg.Channel).Name)))
|
+ GetText(logChannel.Guild, strs.msg_del(((ITextChannel)msg.Channel).Name)))
|
||||||
.WithDescription(msg.Author.ToString()!)
|
.WithDescription(msg.Author.ToString()!)
|
||||||
.AddField(GetText(logChannel.Guild, strs.content),
|
.AddField(GetText(logChannel.Guild, strs.content),
|
||||||
string.IsNullOrWhiteSpace(resolvedMessage) ? "-" : resolvedMessage)
|
string.IsNullOrWhiteSpace(resolvedMessage) ? "-" : resolvedMessage)
|
||||||
.AddField("Id", msg.Id.ToString())
|
.AddField("Id", msg.Id.ToString())
|
||||||
.WithFooter(CurrentTime(channel.Guild));
|
.WithFooter(CurrentTime(channel.Guild));
|
||||||
if (msg.Attachments.Any())
|
if (msg.Attachments.Any())
|
||||||
{
|
{
|
||||||
embed.AddField(GetText(logChannel.Guild, strs.attachments),
|
embed.AddField(GetText(logChannel.Guild, strs.attachments),
|
||||||
@@ -1175,19 +1196,19 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("📝 "
|
.WithTitle("📝 "
|
||||||
+ GetText(logChannel.Guild,
|
+ GetText(logChannel.Guild,
|
||||||
strs.msg_update(((ITextChannel)after.Channel).Name)))
|
strs.msg_update(((ITextChannel)after.Channel).Name)))
|
||||||
.WithDescription(after.Author.ToString()!)
|
.WithDescription(after.Author.ToString()!)
|
||||||
.AddField(GetText(logChannel.Guild, strs.old_msg),
|
.AddField(GetText(logChannel.Guild, strs.old_msg),
|
||||||
string.IsNullOrWhiteSpace(before.Content)
|
string.IsNullOrWhiteSpace(before.Content)
|
||||||
? "-"
|
? "-"
|
||||||
: before.Resolve(TagHandling.FullName))
|
: before.Resolve(TagHandling.FullName))
|
||||||
.AddField(GetText(logChannel.Guild, strs.new_msg),
|
.AddField(GetText(logChannel.Guild, strs.new_msg),
|
||||||
string.IsNullOrWhiteSpace(after.Content) ? "-" : after.Resolve(TagHandling.FullName))
|
string.IsNullOrWhiteSpace(after.Content) ? "-" : after.Resolve(TagHandling.FullName))
|
||||||
.AddField("Id", after.Id.ToString())
|
.AddField("Id", after.Id.ToString())
|
||||||
.WithFooter(CurrentTime(channel.Guild));
|
.WithFooter(CurrentTime(channel.Guild));
|
||||||
|
|
||||||
await logChannel.EmbedAsync(embed);
|
await logChannel.EmbedAsync(embed);
|
||||||
}
|
}
|
||||||
@@ -1252,6 +1273,12 @@ public sealed class LogCommandService : ILogCommandService, IReadyExecutor
|
|||||||
case LogType.UserWarned:
|
case LogType.UserWarned:
|
||||||
id = logSetting.LogWarnsId;
|
id = logSetting.LogWarnsId;
|
||||||
break;
|
break;
|
||||||
|
case LogType.ThreadCreated:
|
||||||
|
id = logSetting.ThreadCreatedId;
|
||||||
|
break;
|
||||||
|
case LogType.ThreadDeleted:
|
||||||
|
id = logSetting.ThreadDeletedId;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (id is null or 0)
|
if (id is null or 0)
|
||||||
|
@@ -143,6 +143,12 @@ public partial class Administration
|
|||||||
return l.LogVoicePresenceTTSId;
|
return l.LogVoicePresenceTTSId;
|
||||||
case LogType.UserMuted:
|
case LogType.UserMuted:
|
||||||
return l.UserMutedId;
|
return l.UserMutedId;
|
||||||
|
case LogType.UserWarned:
|
||||||
|
return l.LogWarnsId;
|
||||||
|
case LogType.ThreadDeleted:
|
||||||
|
return l.ThreadDeletedId;
|
||||||
|
case LogType.ThreadCreated:
|
||||||
|
return l.ThreadCreatedId;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@@ -402,12 +402,21 @@ public partial class Administration
|
|||||||
[UserPerm(GuildPerm.BanMembers)]
|
[UserPerm(GuildPerm.BanMembers)]
|
||||||
[BotPerm(GuildPerm.BanMembers)]
|
[BotPerm(GuildPerm.BanMembers)]
|
||||||
[Priority(1)]
|
[Priority(1)]
|
||||||
public async Task Ban(StoopidTime time, IUser user, [Leftover] string msg = null)
|
public Task Ban(StoopidTime time, IUser user, [Leftover] string msg = null)
|
||||||
|
=> Ban(time, user.Id, msg);
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[RequireContext(ContextType.Guild)]
|
||||||
|
[UserPerm(GuildPerm.BanMembers)]
|
||||||
|
[BotPerm(GuildPerm.BanMembers)]
|
||||||
|
[Priority(0)]
|
||||||
|
public async Task Ban(StoopidTime time, ulong userId, [Leftover] string msg = null)
|
||||||
{
|
{
|
||||||
if (time.Time > TimeSpan.FromDays(49))
|
if (time.Time > TimeSpan.FromDays(49))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var guildUser = await ((DiscordSocketClient)Context.Client).Rest.GetGuildUserAsync(ctx.Guild.Id, user.Id);
|
var guildUser = await ((DiscordSocketClient)Context.Client).Rest.GetGuildUserAsync(ctx.Guild.Id, userId);
|
||||||
|
|
||||||
|
|
||||||
if (guildUser is not null && !await CheckRoleHierarchy(guildUser))
|
if (guildUser is not null && !await CheckRoleHierarchy(guildUser))
|
||||||
return;
|
return;
|
||||||
@@ -429,13 +438,14 @@ public partial class Administration
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var user = await ctx.Client.GetUserAsync(userId);
|
||||||
var banPrune = await _service.GetBanPruneAsync(ctx.Guild.Id) ?? 7;
|
var banPrune = await _service.GetBanPruneAsync(ctx.Guild.Id) ?? 7;
|
||||||
await _mute.TimedBan(ctx.Guild, user, time.Time, (ctx.User + " | " + msg).TrimTo(512), banPrune);
|
await _mute.TimedBan(ctx.Guild, userId, time.Time, (ctx.User + " | " + msg).TrimTo(512), banPrune);
|
||||||
var toSend = _eb.Create()
|
var toSend = _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithTitle("⛔️ " + GetText(strs.banned_user))
|
.WithTitle("⛔️ " + GetText(strs.banned_user))
|
||||||
.AddField(GetText(strs.username), user.ToString(), true)
|
.AddField(GetText(strs.username), user?.ToString() ?? userId.ToString(), true)
|
||||||
.AddField("ID", user.Id.ToString(), true)
|
.AddField("ID", userId.ToString(), true)
|
||||||
.AddField(GetText(strs.duration),
|
.AddField(GetText(strs.duration),
|
||||||
time.Time.Humanize(3, minUnit: TimeUnit.Minute, culture: Culture),
|
time.Time.Humanize(3, minUnit: TimeUnit.Minute, culture: Culture),
|
||||||
true);
|
true);
|
||||||
|
@@ -157,7 +157,7 @@ public class UserPunishService : INService, IReadyExecutor
|
|||||||
if (minutes == 0)
|
if (minutes == 0)
|
||||||
await guild.AddBanAsync(user, reason: reason, pruneDays: banPrune);
|
await guild.AddBanAsync(user, reason: reason, pruneDays: banPrune);
|
||||||
else
|
else
|
||||||
await _mute.TimedBan(user.Guild, user, TimeSpan.FromMinutes(minutes), reason, banPrune);
|
await _mute.TimedBan(user.Guild, user.Id, TimeSpan.FromMinutes(minutes), reason, banPrune);
|
||||||
break;
|
break;
|
||||||
case PunishmentAction.Softban:
|
case PunishmentAction.Softban:
|
||||||
banPrune = await GetBanPruneAsync(user.GuildId) ?? 7;
|
banPrune = await GetBanPruneAsync(user.GuildId) ?? 7;
|
||||||
|
@@ -34,14 +34,14 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
";
|
";
|
||||||
|
|
||||||
private static readonly ISerializer _exportSerializer = new SerializerBuilder()
|
private static readonly ISerializer _exportSerializer = new SerializerBuilder()
|
||||||
.WithEventEmitter(args
|
.WithEventEmitter(args
|
||||||
=> new MultilineScalarFlowStyleEmitter(args))
|
=> new MultilineScalarFlowStyleEmitter(args))
|
||||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||||
.WithIndentedSequences()
|
.WithIndentedSequences()
|
||||||
.ConfigureDefaultValuesHandling(DefaultValuesHandling
|
.ConfigureDefaultValuesHandling(DefaultValuesHandling
|
||||||
.OmitDefaults)
|
.OmitDefaults)
|
||||||
.DisableAliases()
|
.DisableAliases()
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
public int Priority
|
public int Priority
|
||||||
=> 0;
|
=> 0;
|
||||||
@@ -57,8 +57,8 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
// 1. expressions are almost never added (compared to how many times they are being looped through)
|
// 1. expressions are almost never added (compared to how many times they are being looped through)
|
||||||
// 2. only need write locks for this as we'll rebuild+replace the array on every edit
|
// 2. only need write locks for this as we'll rebuild+replace the array on every edit
|
||||||
// 3. there's never many of them (at most a thousand, usually < 100)
|
// 3. there's never many of them (at most a thousand, usually < 100)
|
||||||
private NadekoExpression[] globalExpressions;
|
private NadekoExpression[] globalExpressions = Array.Empty<NadekoExpression>();
|
||||||
private ConcurrentDictionary<ulong, NadekoExpression[]> newguildExpressions;
|
private ConcurrentDictionary<ulong, NadekoExpression[]> newguildExpressions = new();
|
||||||
|
|
||||||
private readonly DbService _db;
|
private readonly DbService _db;
|
||||||
private readonly DiscordSocketClient _client;
|
private readonly DiscordSocketClient _client;
|
||||||
@@ -112,20 +112,20 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
{
|
{
|
||||||
await using var uow = _db.GetDbContext();
|
await using var uow = _db.GetDbContext();
|
||||||
var guildItems = await uow.Expressions.AsNoTracking()
|
var guildItems = await uow.Expressions.AsNoTracking()
|
||||||
.Where(x => allGuildIds.Contains(x.GuildId.Value))
|
.Where(x => allGuildIds.Contains(x.GuildId.Value))
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
newguildExpressions = guildItems.GroupBy(k => k.GuildId!.Value)
|
newguildExpressions = guildItems.GroupBy(k => k.GuildId!.Value)
|
||||||
.ToDictionary(g => g.Key,
|
.ToDictionary(g => g.Key,
|
||||||
g => g.Select(x =>
|
g => g.Select(x =>
|
||||||
{
|
{
|
||||||
x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention);
|
x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention);
|
||||||
return x;
|
return x;
|
||||||
})
|
})
|
||||||
.ToArray())
|
.ToArray())
|
||||||
.ToConcurrent();
|
.ToConcurrent();
|
||||||
|
|
||||||
_disabledGlobalExpressionGuilds = new (await uow.GuildConfigs
|
_disabledGlobalExpressionGuilds = new(await uow.GuildConfigs
|
||||||
.Where(x => x.DisableGlobalExpressions)
|
.Where(x => x.DisableGlobalExpressions)
|
||||||
.Select(x => x.GuildId)
|
.Select(x => x.GuildId)
|
||||||
.ToListAsyncLinqToDB());
|
.ToListAsyncLinqToDB());
|
||||||
@@ -133,14 +133,14 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
lock (_gexprWriteLock)
|
lock (_gexprWriteLock)
|
||||||
{
|
{
|
||||||
var globalItems = uow.Expressions.AsNoTracking()
|
var globalItems = uow.Expressions.AsNoTracking()
|
||||||
.Where(x => x.GuildId == null || x.GuildId == 0)
|
.Where(x => x.GuildId == null || x.GuildId == 0)
|
||||||
.AsEnumerable()
|
.AsEnumerable()
|
||||||
.Select(x =>
|
.Select(x =>
|
||||||
{
|
{
|
||||||
x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention);
|
x.Trigger = x.Trigger.Replace(MENTION_PH, _bot.Mention);
|
||||||
return x;
|
return x;
|
||||||
})
|
})
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
globalExpressions = globalItems;
|
globalExpressions = globalItems;
|
||||||
}
|
}
|
||||||
@@ -509,9 +509,25 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
|
|
||||||
public bool ExpressionExists(ulong? guildId, string input)
|
public bool ExpressionExists(ulong? guildId, string input)
|
||||||
{
|
{
|
||||||
using var uow = _db.GetDbContext();
|
input = input.ToLowerInvariant();
|
||||||
var expr = uow.Expressions.GetByGuildIdAndInput(guildId, input);
|
|
||||||
return expr is not null;
|
var gexprs = globalExpressions;
|
||||||
|
foreach (var t in gexprs)
|
||||||
|
{
|
||||||
|
if (t.Trigger == input)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (guildId is ulong gid && newguildExpressions.TryGetValue(gid, out var guildExprs))
|
||||||
|
{
|
||||||
|
foreach (var t in guildExprs)
|
||||||
|
{
|
||||||
|
if (t.Trigger == input)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string ExportExpressions(ulong? guildId)
|
public string ExportExpressions(ulong? guildId)
|
||||||
@@ -542,17 +558,17 @@ public sealed class NadekoExpressionsService : IExecOnMessage, IReadyExecutor
|
|||||||
{
|
{
|
||||||
var trigger = entry.Key;
|
var trigger = entry.Key;
|
||||||
await uow.Expressions.AddRangeAsync(entry.Value.Where(expr => !string.IsNullOrWhiteSpace(expr.Res))
|
await uow.Expressions.AddRangeAsync(entry.Value.Where(expr => !string.IsNullOrWhiteSpace(expr.Res))
|
||||||
.Select(expr => new NadekoExpression
|
.Select(expr => new NadekoExpression
|
||||||
{
|
{
|
||||||
GuildId = guildId,
|
GuildId = guildId,
|
||||||
Response = expr.Res,
|
Response = expr.Res,
|
||||||
Reactions = expr.React?.Join("@@@"),
|
Reactions = expr.React?.Join("@@@"),
|
||||||
Trigger = trigger,
|
Trigger = trigger,
|
||||||
AllowTarget = expr.At,
|
AllowTarget = expr.At,
|
||||||
ContainsAnywhere = expr.Ca,
|
ContainsAnywhere = expr.Ca,
|
||||||
DmResponse = expr.Dm,
|
DmResponse = expr.Dm,
|
||||||
AutoDeleteTrigger = expr.Ad
|
AutoDeleteTrigger = expr.Ad
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
await uow.SaveChangesAsync();
|
await uow.SaveChangesAsync();
|
||||||
|
@@ -77,28 +77,24 @@ public partial class Gambling
|
|||||||
{
|
{
|
||||||
if (await _bank.TakeAsync(userId, amount))
|
if (await _bank.TakeAsync(userId, amount))
|
||||||
{
|
{
|
||||||
await ReplyErrorLocalizedAsync(strs.take_fail(N(amount),
|
await ctx.OkAsync();
|
||||||
_client.GetUser(userId)?.ToString()
|
|
||||||
?? userId.ToString(),
|
|
||||||
CurrencySign));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await ctx.OkAsync();
|
await ReplyErrorLocalizedAsync(strs.take_fail(N(amount),
|
||||||
|
_client.GetUser(userId)?.ToString()
|
||||||
|
?? userId.ToString(),
|
||||||
|
CurrencySign));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task BankAwardInternalAsync(long amount, ulong userId)
|
private async Task BankAwardInternalAsync(long amount, ulong userId)
|
||||||
{
|
{
|
||||||
if (await _bank.AwardAsync(userId, amount))
|
if (await _bank.AwardAsync(userId, amount))
|
||||||
{
|
{
|
||||||
await ReplyErrorLocalizedAsync(strs.take_fail(N(amount),
|
await ctx.OkAsync();
|
||||||
_client.GetUser(userId)?.ToString()
|
|
||||||
?? userId.ToString(),
|
|
||||||
CurrencySign));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await ctx.OkAsync();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
|
@@ -239,7 +239,7 @@ public partial class Gambling : GamblingModule<GamblingService>
|
|||||||
|
|
||||||
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
|
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
|
||||||
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
|
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
|
||||||
$"**{usr.Username}#{usr.Discriminator}**",
|
$"**{usr.Username}**",
|
||||||
footer: $"ID: {usr.Id}");
|
footer: $"ID: {usr.Id}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,7 +258,7 @@ public partial class Gambling : GamblingModule<GamblingService>
|
|||||||
|
|
||||||
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
|
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
|
||||||
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
|
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
|
||||||
$"**{usr.Username}#{usr.Discriminator}**",
|
$"**{usr.Username}**",
|
||||||
footer: $"ID: {usr.Id}");
|
footer: $"ID: {usr.Id}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -840,7 +840,7 @@ public partial class Gambling : GamblingModule<GamblingService>
|
|||||||
else if (result.Result == RpsResultType.Win)
|
else if (result.Result == RpsResultType.Win)
|
||||||
{
|
{
|
||||||
if ((long)result.Won > 0)
|
if ((long)result.Won > 0)
|
||||||
embed.AddField(GetText(strs.won), N(amount.Value));
|
embed.AddField(GetText(strs.won), N((long)result.Won));
|
||||||
|
|
||||||
msg = GetText(strs.rps_win(ctx.User.Mention,
|
msg = GetText(strs.rps_win(ctx.User.Mention,
|
||||||
GetRpsPick(pick),
|
GetRpsPick(pick),
|
||||||
|
@@ -250,8 +250,9 @@ public partial class Gambling
|
|||||||
? "-"
|
? "-"
|
||||||
: string.Join("\n",
|
: string.Join("\n",
|
||||||
itemList.Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _))
|
itemList.Where(x => waifuItems.TryGetValue(x.ItemEmoji, out _))
|
||||||
.OrderBy(x => waifuItems[x.ItemEmoji].Price)
|
.OrderByDescending(x => waifuItems[x.ItemEmoji].Price)
|
||||||
.GroupBy(x => x.ItemEmoji)
|
.GroupBy(x => x.ItemEmoji)
|
||||||
|
.Take(60)
|
||||||
.Select(x => $"{x.Key} x{x.Count(),-3}")
|
.Select(x => $"{x.Key} x{x.Count(),-3}")
|
||||||
.Chunk(2)
|
.Chunk(2)
|
||||||
.Select(x => string.Join(" ", x)));
|
.Select(x => string.Join(" ", x)));
|
||||||
@@ -264,7 +265,10 @@ public partial class Gambling
|
|||||||
|
|
||||||
var fansList = await _service.GetFansNames(wi.WaifuId);
|
var fansList = await _service.GetFansNames(wi.WaifuId);
|
||||||
var fansStr = fansList
|
var fansStr = fansList
|
||||||
.Select((x) => claimsNames.Contains(x) ? $"{x} 💞" : x).Join('\n');
|
.Shuffle()
|
||||||
|
.Take(30)
|
||||||
|
.Select((x) => claimsNames.Contains(x) ? $"{x} 💞" : x)
|
||||||
|
.Join('\n');
|
||||||
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(fansStr))
|
if (string.IsNullOrWhiteSpace(fansStr))
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using NadekoBot.Common.ModuleBehaviors;
|
using NadekoBot.Common.ModuleBehaviors;
|
||||||
using NadekoBot.Db.Models;
|
using NadekoBot.Db.Models;
|
||||||
|
using NadekoBot.Modules.Games.Common;
|
||||||
using NadekoBot.Modules.Games.Common.ChatterBot;
|
using NadekoBot.Modules.Games.Common.ChatterBot;
|
||||||
using NadekoBot.Modules.Permissions;
|
using NadekoBot.Modules.Permissions;
|
||||||
using NadekoBot.Modules.Permissions.Common;
|
using NadekoBot.Modules.Permissions.Common;
|
||||||
@@ -27,6 +28,7 @@ public class ChatterBotService : IExecOnMessage
|
|||||||
private readonly IHttpClientFactory _httpFactory;
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
private readonly IPatronageService _ps;
|
private readonly IPatronageService _ps;
|
||||||
private readonly CmdCdService _ccs;
|
private readonly CmdCdService _ccs;
|
||||||
|
private readonly GamesConfigService _gcs;
|
||||||
|
|
||||||
public ChatterBotService(
|
public ChatterBotService(
|
||||||
DiscordSocketClient client,
|
DiscordSocketClient client,
|
||||||
@@ -38,7 +40,8 @@ public class ChatterBotService : IExecOnMessage
|
|||||||
IBotCredentials creds,
|
IBotCredentials creds,
|
||||||
IEmbedBuilderService eb,
|
IEmbedBuilderService eb,
|
||||||
IPatronageService ps,
|
IPatronageService ps,
|
||||||
CmdCdService cmdCdService)
|
CmdCdService cmdCdService,
|
||||||
|
GamesConfigService gcs)
|
||||||
{
|
{
|
||||||
_client = client;
|
_client = client;
|
||||||
_perms = perms;
|
_perms = perms;
|
||||||
@@ -49,6 +52,7 @@ public class ChatterBotService : IExecOnMessage
|
|||||||
_httpFactory = factory;
|
_httpFactory = factory;
|
||||||
_ps = ps;
|
_ps = ps;
|
||||||
_ccs = cmdCdService;
|
_ccs = cmdCdService;
|
||||||
|
_gcs = gcs;
|
||||||
|
|
||||||
_flKey = new FeatureLimitKey()
|
_flKey = new FeatureLimitKey()
|
||||||
{
|
{
|
||||||
@@ -64,11 +68,30 @@ public class ChatterBotService : IExecOnMessage
|
|||||||
|
|
||||||
public IChatterBotSession CreateSession()
|
public IChatterBotSession CreateSession()
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrWhiteSpace(_creds.CleverbotApiKey))
|
switch (_gcs.Data.ChatBot)
|
||||||
return new OfficialCleverbotSession(_creds.CleverbotApiKey, _httpFactory);
|
{
|
||||||
|
case ChatBotImplementation.Cleverbot:
|
||||||
|
if (!string.IsNullOrWhiteSpace(_creds.CleverbotApiKey))
|
||||||
|
return new OfficialCleverbotSession(_creds.CleverbotApiKey, _httpFactory);
|
||||||
|
|
||||||
Log.Information("Cleverbot will not work as the api key is missing.");
|
Log.Information("Cleverbot will not work as the api key is missing.");
|
||||||
return null;
|
return null;
|
||||||
|
case ChatBotImplementation.Gpt3:
|
||||||
|
if (!string.IsNullOrWhiteSpace(_creds.Gpt3ApiKey))
|
||||||
|
return new OfficialGpt3Session(_creds.Gpt3ApiKey,
|
||||||
|
_gcs.Data.ChatGpt.ModelName,
|
||||||
|
_gcs.Data.ChatGpt.ChatHistory,
|
||||||
|
_gcs.Data.ChatGpt.MaxTokens,
|
||||||
|
_gcs.Data.ChatGpt.MinTokens,
|
||||||
|
_gcs.Data.ChatGpt.PersonalityPrompt,
|
||||||
|
_client.CurrentUser.Username,
|
||||||
|
_httpFactory);
|
||||||
|
|
||||||
|
Log.Information("Gpt3 will not work as the api key is missing.");
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public string PrepareMessage(IUserMessage msg, out IChatterBotSession cleverbot)
|
public string PrepareMessage(IUserMessage msg, out IChatterBotSession cleverbot)
|
||||||
@@ -180,12 +203,12 @@ public class ChatterBotService : IExecOnMessage
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ = channel.TriggerTypingAsync();
|
_ = channel.TriggerTypingAsync();
|
||||||
var response = await cbs.Think(message);
|
var response = await cbs.Think(message, usrMsg.Author.ToString());
|
||||||
await channel.SendConfirmAsync(_eb,
|
await channel.SendConfirmAsync(_eb,
|
||||||
title: null,
|
title: null,
|
||||||
response.SanitizeMentions(true)
|
response.SanitizeMentions(true)
|
||||||
// , footer: counter > 0 ? counter.ToString() : null
|
// , footer: counter > 0 ? counter.ToString() : null
|
||||||
);
|
);
|
||||||
|
|
||||||
Log.Information(@"CleverBot Executed
|
Log.Information(@"CleverBot Executed
|
||||||
Server: {GuildName} [{GuildId}]
|
Server: {GuildName} [{GuildId}]
|
||||||
|
@@ -1,8 +0,0 @@
|
|||||||
#nullable disable
|
|
||||||
namespace NadekoBot.Modules.Games.Common.ChatterBot;
|
|
||||||
|
|
||||||
public class ChatterBotResponse
|
|
||||||
{
|
|
||||||
public string Convo_id { get; set; }
|
|
||||||
public string BotSay { get; set; }
|
|
||||||
}
|
|
@@ -0,0 +1,46 @@
|
|||||||
|
#nullable disable
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace NadekoBot.Modules.Games.Common.ChatterBot;
|
||||||
|
|
||||||
|
public class Gpt3Response
|
||||||
|
{
|
||||||
|
[JsonPropertyName("choices")]
|
||||||
|
public Choice[] Choices { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Choice
|
||||||
|
{
|
||||||
|
[JsonPropertyName("message")]
|
||||||
|
public Message Message { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Message {
|
||||||
|
[JsonPropertyName("content")]
|
||||||
|
public string Content { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Gpt3ApiRequest
|
||||||
|
{
|
||||||
|
[JsonPropertyName("model")]
|
||||||
|
public string Model { get; init; }
|
||||||
|
|
||||||
|
[JsonPropertyName("messages")]
|
||||||
|
public List<GPTMessage> Messages { get; init; }
|
||||||
|
|
||||||
|
[JsonPropertyName("temperature")]
|
||||||
|
public int Temperature { get; init; }
|
||||||
|
|
||||||
|
[JsonPropertyName("max_tokens")]
|
||||||
|
public int MaxTokens { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class GPTMessage
|
||||||
|
{
|
||||||
|
[JsonPropertyName("role")]
|
||||||
|
public string Role {get; init;}
|
||||||
|
[JsonPropertyName("content")]
|
||||||
|
public string Content {get; init;}
|
||||||
|
[JsonPropertyName("name")]
|
||||||
|
public string Name {get; init;}
|
||||||
|
}
|
@@ -3,5 +3,5 @@ namespace NadekoBot.Modules.Games.Common.ChatterBot;
|
|||||||
|
|
||||||
public interface IChatterBotSession
|
public interface IChatterBotSession
|
||||||
{
|
{
|
||||||
Task<string> Think(string input);
|
Task<string> Think(string input, string username);
|
||||||
}
|
}
|
@@ -18,7 +18,7 @@ public class OfficialCleverbotSession : IChatterBotSession
|
|||||||
_httpFactory = factory;
|
_httpFactory = factory;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<string> Think(string input)
|
public async Task<string> Think(string input, string username)
|
||||||
{
|
{
|
||||||
using var http = _httpFactory.CreateClient();
|
using var http = _httpFactory.CreateClient();
|
||||||
var dataString = await http.GetStringAsync(string.Format(QueryString, input, cs ?? ""));
|
var dataString = await http.GetStringAsync(string.Format(QueryString, input, cs ?? ""));
|
||||||
|
@@ -0,0 +1,107 @@
|
|||||||
|
#nullable disable
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using SharpToken;
|
||||||
|
using Antlr.Runtime;
|
||||||
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||||
|
|
||||||
|
namespace NadekoBot.Modules.Games.Common.ChatterBot;
|
||||||
|
|
||||||
|
public class OfficialGpt3Session : IChatterBotSession
|
||||||
|
{
|
||||||
|
private string Uri
|
||||||
|
=> $"https://api.openai.com/v1/chat/completions";
|
||||||
|
|
||||||
|
private readonly string _apiKey;
|
||||||
|
private readonly string _model;
|
||||||
|
private readonly int _maxHistory;
|
||||||
|
private readonly int _maxTokens;
|
||||||
|
private readonly int _minTokens;
|
||||||
|
private readonly string _nadekoUsername;
|
||||||
|
private readonly GptEncoding _encoding;
|
||||||
|
private List<GPTMessage> messages = new();
|
||||||
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public OfficialGpt3Session(
|
||||||
|
string apiKey,
|
||||||
|
ChatGptModel model,
|
||||||
|
int chatHistory,
|
||||||
|
int maxTokens,
|
||||||
|
int minTokens,
|
||||||
|
string personality,
|
||||||
|
string nadekoUsername,
|
||||||
|
IHttpClientFactory factory)
|
||||||
|
{
|
||||||
|
_apiKey = apiKey;
|
||||||
|
_httpFactory = factory;
|
||||||
|
switch (model)
|
||||||
|
{
|
||||||
|
case ChatGptModel.Gpt35Turbo:
|
||||||
|
_model = "gpt-3.5-turbo";
|
||||||
|
break;
|
||||||
|
case ChatGptModel.Gpt4:
|
||||||
|
_model = "gpt-4";
|
||||||
|
break;
|
||||||
|
case ChatGptModel.Gpt432k:
|
||||||
|
_model = "gpt-4-32k";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_maxHistory = chatHistory;
|
||||||
|
_maxTokens = maxTokens;
|
||||||
|
_minTokens = minTokens;
|
||||||
|
_nadekoUsername = nadekoUsername;
|
||||||
|
_encoding = GptEncoding.GetEncodingForModel(_model);
|
||||||
|
messages.Add(new GPTMessage(){Role = "user", Content = personality, Name = _nadekoUsername});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> Think(string input, string username)
|
||||||
|
{
|
||||||
|
messages.Add(new GPTMessage(){Role = "user", Content = input, Name = username});
|
||||||
|
while(messages.Count > _maxHistory + 2){
|
||||||
|
messages.RemoveAt(1);
|
||||||
|
}
|
||||||
|
int tokensUsed = 0;
|
||||||
|
foreach(GPTMessage message in messages){
|
||||||
|
tokensUsed += _encoding.Encode(message.Content).Count;
|
||||||
|
}
|
||||||
|
tokensUsed *= 2; //Unsure why this is the case, but the token count chatgpt reports back is double what I calculate.
|
||||||
|
//check if we have the minimum number of tokens available to use. Remove messages until we have enough, otherwise exit out and inform the user why.
|
||||||
|
while(_maxTokens - tokensUsed <= _minTokens){
|
||||||
|
if(messages.Count > 2){
|
||||||
|
int tokens = _encoding.Encode(messages[1].Content).Count * 2;
|
||||||
|
tokensUsed -= tokens;
|
||||||
|
messages.RemoveAt(1);
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
return "Token count exceeded, please increase the number of tokens in the bot config and restart.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
using var http = _httpFactory.CreateClient();
|
||||||
|
http.DefaultRequestHeaders.Authorization = new("Bearer", _apiKey);
|
||||||
|
var data = await http.PostAsJsonAsync(Uri, new Gpt3ApiRequest()
|
||||||
|
{
|
||||||
|
Model = _model,
|
||||||
|
Messages = messages,
|
||||||
|
MaxTokens = _maxTokens - tokensUsed,
|
||||||
|
Temperature = 1,
|
||||||
|
});
|
||||||
|
var dataString = await data.Content.ReadAsStringAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var response = JsonConvert.DeserializeObject<Gpt3Response>(dataString);
|
||||||
|
string message = response?.Choices[0]?.Message?.Content;
|
||||||
|
//Can't rely on the return to except, now that we need to add it to the messages list.
|
||||||
|
_ = message ?? throw new ArgumentNullException(nameof(message));
|
||||||
|
messages.Add(new GPTMessage(){Role = "assistant", Content = message, Name = _nadekoUsername});
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
Log.Warning("Unexpected GPT-3 response received: {ResponseString}", dataString);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@@ -8,7 +8,7 @@ namespace NadekoBot.Modules.Games.Common;
|
|||||||
public sealed partial class GamesConfig : ICloneable<GamesConfig>
|
public sealed partial class GamesConfig : ICloneable<GamesConfig>
|
||||||
{
|
{
|
||||||
[Comment("DO NOT CHANGE")]
|
[Comment("DO NOT CHANGE")]
|
||||||
public int Version { get; set; }
|
public int Version { get; set; } = 3;
|
||||||
|
|
||||||
[Comment("Hangman related settings (.hangman command)")]
|
[Comment("Hangman related settings (.hangman command)")]
|
||||||
public HangmanConfig Hangman { get; set; } = new()
|
public HangmanConfig Hangman { get; set; } = new()
|
||||||
@@ -95,6 +95,35 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
|
|||||||
Name = "Unicorn"
|
Name = "Unicorn"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
[Comment(@"Which chatbot API should bot use.
|
||||||
|
'cleverbot' - bot will use Cleverbot API.
|
||||||
|
'gpt3' - bot will use GPT-3 API")]
|
||||||
|
public ChatBotImplementation ChatBot { get; set; } = ChatBotImplementation.Gpt3;
|
||||||
|
|
||||||
|
public ChatGptConfig ChatGpt { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Cloneable]
|
||||||
|
public sealed partial class ChatGptConfig
|
||||||
|
{
|
||||||
|
[Comment(@"Which GPT-3 Model should bot use.
|
||||||
|
gpt35turbo - cheapest
|
||||||
|
gpt4 - 30x more expensive, higher quality
|
||||||
|
gp432k - same model as above, but with a 32k token limit")]
|
||||||
|
public ChatGptModel ModelName { get; set; } = ChatGptModel.Gpt35Turbo;
|
||||||
|
|
||||||
|
[Comment(@"How should the chat bot behave, what's its personality? (Usage of this counts towards the max tokens)")]
|
||||||
|
public string PersonalityPrompt { get; set; } = "You are a chat bot willing to have a conversation with anyone about anything.";
|
||||||
|
|
||||||
|
[Comment(@"The maximum number of messages in a conversation that can be remembered. (This will increase the number of tokens used)")]
|
||||||
|
public int ChatHistory { get; set; } = 5;
|
||||||
|
|
||||||
|
[Comment(@"The maximum number of tokens to use per GPT-3 API call")]
|
||||||
|
public int MaxTokens { get; set; } = 100;
|
||||||
|
|
||||||
|
[Comment(@"The minimum number of tokens to use per GPT-3 API call, such that chat history is removed to make room.")]
|
||||||
|
public int MinTokens { get; set; } = 30;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Cloneable]
|
[Cloneable]
|
||||||
@@ -121,3 +150,16 @@ public sealed partial class RaceAnimal
|
|||||||
public string Icon { get; set; }
|
public string Icon { get; set; }
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public enum ChatBotImplementation
|
||||||
|
{
|
||||||
|
Cleverbot,
|
||||||
|
Gpt3
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum ChatGptModel
|
||||||
|
{
|
||||||
|
Gpt35Turbo,
|
||||||
|
Gpt4,
|
||||||
|
Gpt432k
|
||||||
|
}
|
@@ -28,6 +28,33 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
|
|||||||
long.TryParse,
|
long.TryParse,
|
||||||
ConfigPrinters.ToString,
|
ConfigPrinters.ToString,
|
||||||
val => val >= 0);
|
val => val >= 0);
|
||||||
|
AddParsedProp("chatbot",
|
||||||
|
gs => gs.ChatBot,
|
||||||
|
ConfigParsers.InsensitiveEnum,
|
||||||
|
ConfigPrinters.ToString);
|
||||||
|
AddParsedProp("gpt.modelName",
|
||||||
|
gs => gs.ChatGpt.ModelName,
|
||||||
|
ConfigParsers.InsensitiveEnum,
|
||||||
|
ConfigPrinters.ToString);
|
||||||
|
AddParsedProp("gpt.personality",
|
||||||
|
gs => gs.ChatGpt.PersonalityPrompt,
|
||||||
|
ConfigParsers.String,
|
||||||
|
ConfigPrinters.ToString);
|
||||||
|
AddParsedProp("gpt.chathistory",
|
||||||
|
gs => gs.ChatGpt.ChatHistory,
|
||||||
|
int.TryParse,
|
||||||
|
ConfigPrinters.ToString,
|
||||||
|
val => val > 0);
|
||||||
|
AddParsedProp("gpt.max_tokens",
|
||||||
|
gs => gs.ChatGpt.MaxTokens,
|
||||||
|
int.TryParse,
|
||||||
|
ConfigPrinters.ToString,
|
||||||
|
val => val > 0);
|
||||||
|
AddParsedProp("gpt.min_tokens",
|
||||||
|
gs => gs.ChatGpt.MinTokens,
|
||||||
|
int.TryParse,
|
||||||
|
ConfigPrinters.ToString,
|
||||||
|
val => val > 0);
|
||||||
|
|
||||||
Migrate();
|
Migrate();
|
||||||
}
|
}
|
||||||
@@ -45,5 +72,23 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.Version < 2)
|
||||||
|
{
|
||||||
|
ModifyConfig(c =>
|
||||||
|
{
|
||||||
|
c.Version = 2;
|
||||||
|
c.ChatBot = ChatBotImplementation.Cleverbot;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.Version < 3)
|
||||||
|
{
|
||||||
|
ModifyConfig(c =>
|
||||||
|
{
|
||||||
|
c.Version = 3;
|
||||||
|
c.ChatGpt.ModelName = ChatGptModel.Gpt35Turbo;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -23,7 +23,6 @@ public class GamesService : INService, IReadyExecutor
|
|||||||
|
|
||||||
//channelId, game
|
//channelId, game
|
||||||
public ConcurrentDictionary<ulong, AcrophobiaGame> AcrophobiaGames { get; } = new();
|
public ConcurrentDictionary<ulong, AcrophobiaGame> AcrophobiaGames { get; } = new();
|
||||||
public ConcurrentDictionary<ulong, TriviaGame> RunningTrivias { get; } = new();
|
|
||||||
public Dictionary<ulong, TicTacToe> TicTacToeGames { get; } = new();
|
public Dictionary<ulong, TicTacToe> TicTacToeGames { get; } = new();
|
||||||
public ConcurrentDictionary<ulong, TypingGame> RunningContests { get; } = new();
|
public ConcurrentDictionary<ulong, TypingGame> RunningContests { get; } = new();
|
||||||
public ConcurrentDictionary<ulong, NunchiGame> NunchiGames { get; } = new();
|
public ConcurrentDictionary<ulong, NunchiGame> NunchiGames { get; } = new();
|
||||||
|
@@ -36,7 +36,7 @@ public partial class Games
|
|||||||
var (opts, _) = OptionsParser.ParseFrom(new TriviaOptions(), args);
|
var (opts, _) = OptionsParser.ParseFrom(new TriviaOptions(), args);
|
||||||
|
|
||||||
var config = _gamesConfig.Data;
|
var config = _gamesConfig.Data;
|
||||||
if (config.Trivia.MinimumWinReq > 0 && config.Trivia.MinimumWinReq > opts.WinRequirement)
|
if (opts.WinRequirement != 0 && config.Trivia.MinimumWinReq > 0 && config.Trivia.MinimumWinReq > opts.WinRequirement)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var trivia = new TriviaGame(opts, _cache);
|
var trivia = new TriviaGame(opts, _cache);
|
||||||
|
@@ -157,7 +157,7 @@ public sealed class TriviaGame
|
|||||||
|
|
||||||
var isWin = false;
|
var isWin = false;
|
||||||
// if user won the game, tell the game to stop
|
// if user won the game, tell the game to stop
|
||||||
if (val >= _opts.WinRequirement)
|
if (_opts.WinRequirement != 0 && val >= _opts.WinRequirement)
|
||||||
{
|
{
|
||||||
_isStopped = true;
|
_isStopped = true;
|
||||||
isWin = true;
|
isWin = true;
|
||||||
|
@@ -292,7 +292,7 @@ public partial class Help : NadekoModule<HelpService>
|
|||||||
.WithTitle(GetText(strs.cmd_group_commands(group.Name)))
|
.WithTitle(GetText(strs.cmd_group_commands(group.Name)))
|
||||||
.WithOkColor();
|
.WithOkColor();
|
||||||
|
|
||||||
foreach (var cmd in group.Commands)
|
foreach (var cmd in group.Commands.DistinctBy(x => x.Aliases[0]))
|
||||||
{
|
{
|
||||||
eb.AddField(prefix + cmd.Aliases.First(), cmd.RealSummary(_strings, _medusae, Culture, prefix));
|
eb.AddField(prefix + cmd.Aliases.First(), cmd.RealSummary(_strings, _medusae, Culture, prefix));
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
using NadekoBot.Modules.Searches;
|
||||||
|
|
||||||
namespace NadekoBot.Modules.Music;
|
namespace NadekoBot.Modules.Music;
|
||||||
|
|
||||||
@@ -27,11 +28,12 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
|
|||||||
|
|
||||||
private readonly IGoogleApiService _google;
|
private readonly IGoogleApiService _google;
|
||||||
|
|
||||||
public YtdlYoutubeResolver(ITrackCacher trackCacher, IGoogleApiService google)
|
public YtdlYoutubeResolver(ITrackCacher trackCacher, IGoogleApiService google, SearchesConfigService scs)
|
||||||
{
|
{
|
||||||
_trackCacher = trackCacher;
|
_trackCacher = trackCacher;
|
||||||
_google = google;
|
_google = google;
|
||||||
|
|
||||||
|
|
||||||
_ytdlPlaylistOperation = new("-4 "
|
_ytdlPlaylistOperation = new("-4 "
|
||||||
+ "--geo-bypass "
|
+ "--geo-bypass "
|
||||||
+ "--encoding UTF8 "
|
+ "--encoding UTF8 "
|
||||||
@@ -44,7 +46,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
|
|||||||
+ "--no-check-certificate "
|
+ "--no-check-certificate "
|
||||||
+ "-i "
|
+ "-i "
|
||||||
+ "--yes-playlist "
|
+ "--yes-playlist "
|
||||||
+ "-- \"{0}\"");
|
+ "-- \"{0}\"", scs.Data.YtProvider != YoutubeSearcher.Ytdl);
|
||||||
|
|
||||||
_ytdlIdOperation = new("-4 "
|
_ytdlIdOperation = new("-4 "
|
||||||
+ "--geo-bypass "
|
+ "--geo-bypass "
|
||||||
@@ -56,7 +58,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
|
|||||||
+ "--get-thumbnail "
|
+ "--get-thumbnail "
|
||||||
+ "--get-duration "
|
+ "--get-duration "
|
||||||
+ "--no-check-certificate "
|
+ "--no-check-certificate "
|
||||||
+ "-- \"{0}\"");
|
+ "-- \"{0}\"", scs.Data.YtProvider != YoutubeSearcher.Ytdl);
|
||||||
|
|
||||||
_ytdlSearchOperation = new("-4 "
|
_ytdlSearchOperation = new("-4 "
|
||||||
+ "--geo-bypass "
|
+ "--geo-bypass "
|
||||||
@@ -69,7 +71,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
|
|||||||
+ "--get-duration "
|
+ "--get-duration "
|
||||||
+ "--no-check-certificate "
|
+ "--no-check-certificate "
|
||||||
+ "--default-search "
|
+ "--default-search "
|
||||||
+ "\"ytsearch:\" -- \"{0}\"");
|
+ "\"ytsearch:\" -- \"{0}\"", scs.Data.YtProvider != YoutubeSearcher.Ytdl);
|
||||||
}
|
}
|
||||||
|
|
||||||
private YtTrackData ResolveYtdlData(string ytdlOutputString)
|
private YtTrackData ResolveYtdlData(string ytdlOutputString)
|
||||||
|
@@ -22,6 +22,6 @@ public interface ISearchImagesService
|
|||||||
ValueTask<bool> ToggleBlacklistTag(ulong guildId, string tag);
|
ValueTask<bool> ToggleBlacklistTag(ulong guildId, string tag);
|
||||||
ValueTask<string[]> GetBlacklistedTags(ulong guildId);
|
ValueTask<string[]> GetBlacklistedTags(ulong guildId);
|
||||||
Task<UrlReply> Butts();
|
Task<UrlReply> Butts();
|
||||||
Task<Gallery> GetNhentaiByIdAsync(uint id);
|
// Task<Gallery> GetNhentaiByIdAsync(uint id);
|
||||||
Task<Gallery> GetNhentaiBySearchAsync(string search);
|
// Task<Gallery> GetNhentaiBySearchAsync(string search);
|
||||||
}
|
}
|
@@ -1,9 +1,9 @@
|
|||||||
using NadekoBot.Modules.Searches.Common;
|
// using NadekoBot.Modules.Searches.Common;
|
||||||
|
//
|
||||||
namespace NadekoBot.Modules.Nsfw;
|
// namespace NadekoBot.Modules.Nsfw;
|
||||||
|
//
|
||||||
public interface INhentaiService
|
// public interface INhentaiService
|
||||||
{
|
// {
|
||||||
Task<Gallery?> GetAsync(uint id);
|
// Task<Gallery?> GetAsync(uint id);
|
||||||
Task<IReadOnlyList<uint>> GetIdsBySearchAsync(string search);
|
// Task<IReadOnlyList<uint>> GetIdsBySearchAsync(string search);
|
||||||
}
|
// }
|
@@ -1,115 +1,115 @@
|
|||||||
using AngleSharp.Html.Dom;
|
// using AngleSharp.Html.Dom;
|
||||||
using AngleSharp.Html.Parser;
|
// using AngleSharp.Html.Parser;
|
||||||
using NadekoBot.Modules.Searches.Common;
|
// using NadekoBot.Modules.Searches.Common;
|
||||||
|
//
|
||||||
namespace NadekoBot.Modules.Nsfw;
|
// namespace NadekoBot.Modules.Nsfw;
|
||||||
|
//
|
||||||
public sealed class NhentaiScraperService : INhentaiService, INService
|
// public sealed class NhentaiScraperService : INhentaiService, INService
|
||||||
{
|
// {
|
||||||
private readonly IHttpClientFactory _httpFactory;
|
// private readonly IHttpClientFactory _httpFactory;
|
||||||
|
//
|
||||||
private static readonly HtmlParser _htmlParser = new(new()
|
// private static readonly HtmlParser _htmlParser = new(new()
|
||||||
{
|
// {
|
||||||
IsScripting = false,
|
// IsScripting = false,
|
||||||
IsEmbedded = false,
|
// IsEmbedded = false,
|
||||||
IsSupportingProcessingInstructions = false,
|
// IsSupportingProcessingInstructions = false,
|
||||||
IsKeepingSourceReferences = false,
|
// IsKeepingSourceReferences = false,
|
||||||
IsNotSupportingFrames = true
|
// IsNotSupportingFrames = true
|
||||||
});
|
// });
|
||||||
|
//
|
||||||
public NhentaiScraperService(IHttpClientFactory httpFactory)
|
// public NhentaiScraperService(IHttpClientFactory httpFactory)
|
||||||
{
|
// {
|
||||||
_httpFactory = httpFactory;
|
// _httpFactory = httpFactory;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
private HttpClient GetHttpClient()
|
// private HttpClient GetHttpClient()
|
||||||
{
|
// {
|
||||||
var http = _httpFactory.CreateClient();
|
// var http = _httpFactory.CreateClient();
|
||||||
http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36");
|
// http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36");
|
||||||
http.DefaultRequestHeaders.Add("Cookie", "cf_clearance=I5pR71P4wJkRBFTLFjBndI.GwfKwT.Gx06uS8XNmRJo-1657214595-0-150; csrftoken=WMWRLtsQtBVQYvYkbqXKJHI9T1JwWCdd3tNhoxHn7aHLUYHAqe60XFUKAoWsJtda");
|
// http.DefaultRequestHeaders.Add("Cookie", "cf_clearance=I5pR71P4wJkRBFTLFjBndI.GwfKwT.Gx06uS8XNmRJo-1657214595-0-150; csrftoken=WMWRLtsQtBVQYvYkbqXKJHI9T1JwWCdd3tNhoxHn7aHLUYHAqe60XFUKAoWsJtda");
|
||||||
return http;
|
// return http;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
public async Task<Gallery?> GetAsync(uint id)
|
// public async Task<Gallery?> GetAsync(uint id)
|
||||||
{
|
// {
|
||||||
using var http = GetHttpClient();
|
// using var http = GetHttpClient();
|
||||||
try
|
// try
|
||||||
{
|
// {
|
||||||
var url = $"https://nhentai.net/g/{id}/";
|
// var url = $"https://nhentai.net/g/{id}/";
|
||||||
var strRes = await http.GetStringAsync(url);
|
// var strRes = await http.GetStringAsync(url);
|
||||||
var doc = await _htmlParser.ParseDocumentAsync(strRes);
|
// var doc = await _htmlParser.ParseDocumentAsync(strRes);
|
||||||
|
//
|
||||||
var title = doc.QuerySelector("#info .title")?.TextContent;
|
// var title = doc.QuerySelector("#info .title")?.TextContent;
|
||||||
var fullTitle = doc.QuerySelector("meta[itemprop=\"name\"]")?.Attributes["content"]?.Value
|
// var fullTitle = doc.QuerySelector("meta[itemprop=\"name\"]")?.Attributes["content"]?.Value
|
||||||
?? title;
|
// ?? title;
|
||||||
var thumb = (doc.QuerySelector("#cover a img") as IHtmlImageElement)?.Dataset["src"];
|
// var thumb = (doc.QuerySelector("#cover a img") as IHtmlImageElement)?.Dataset["src"];
|
||||||
|
//
|
||||||
var tagsElem = doc.QuerySelector("#tags");
|
// var tagsElem = doc.QuerySelector("#tags");
|
||||||
|
//
|
||||||
var pageCount = tagsElem?.QuerySelector("a.tag[href^=\"/search/?q=pages\"] span")?.TextContent;
|
// var pageCount = tagsElem?.QuerySelector("a.tag[href^=\"/search/?q=pages\"] span")?.TextContent;
|
||||||
var likes = doc.QuerySelector(".buttons .btn-disabled.btn.tooltip span span")?.TextContent?.Trim('(', ')');
|
// var likes = doc.QuerySelector(".buttons .btn-disabled.btn.tooltip span span")?.TextContent?.Trim('(', ')');
|
||||||
var uploadedAt = (tagsElem?.QuerySelector(".tag-container .tags time.nobold") as IHtmlTimeElement)?.DateTime;
|
// var uploadedAt = (tagsElem?.QuerySelector(".tag-container .tags time.nobold") as IHtmlTimeElement)?.DateTime;
|
||||||
|
//
|
||||||
var tags = tagsElem?.QuerySelectorAll(".tag-container .tags > a.tag[href^=\"/tag\"]")
|
// var tags = tagsElem?.QuerySelectorAll(".tag-container .tags > a.tag[href^=\"/tag\"]")
|
||||||
.Cast<IHtmlAnchorElement>()
|
// .Cast<IHtmlAnchorElement>()
|
||||||
.Select(x => new Tag()
|
// .Select(x => new Tag()
|
||||||
{
|
// {
|
||||||
Name = x.QuerySelector("span:first-child")?.TextContent,
|
// Name = x.QuerySelector("span:first-child")?.TextContent,
|
||||||
Url = $"https://nhentai.net{x.PathName}"
|
// Url = $"https://nhentai.net{x.PathName}"
|
||||||
})
|
// })
|
||||||
.ToArray();
|
// .ToArray();
|
||||||
|
//
|
||||||
if (string.IsNullOrWhiteSpace(fullTitle))
|
// if (string.IsNullOrWhiteSpace(fullTitle))
|
||||||
return null;
|
// return null;
|
||||||
|
//
|
||||||
if (!int.TryParse(pageCount, out var pc))
|
// if (!int.TryParse(pageCount, out var pc))
|
||||||
return null;
|
// return null;
|
||||||
|
//
|
||||||
if (!int.TryParse(likes, out var lc))
|
// if (!int.TryParse(likes, out var lc))
|
||||||
return null;
|
// return null;
|
||||||
|
//
|
||||||
if (!DateTime.TryParse(uploadedAt, out var ua))
|
// if (!DateTime.TryParse(uploadedAt, out var ua))
|
||||||
return null;
|
// return null;
|
||||||
|
//
|
||||||
return new Gallery(id,
|
// return new Gallery(id,
|
||||||
url,
|
// url,
|
||||||
fullTitle,
|
// fullTitle,
|
||||||
title,
|
// title,
|
||||||
thumb,
|
// thumb,
|
||||||
pc,
|
// pc,
|
||||||
lc,
|
// lc,
|
||||||
ua,
|
// ua,
|
||||||
tags);
|
// tags);
|
||||||
}
|
// }
|
||||||
catch (HttpRequestException)
|
// catch (HttpRequestException)
|
||||||
{
|
// {
|
||||||
Log.Warning("Nhentai with id {NhentaiId} not found", id);
|
// Log.Warning("Nhentai with id {NhentaiId} not found", id);
|
||||||
return null;
|
// return null;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
public async Task<IReadOnlyList<uint>> GetIdsBySearchAsync(string search)
|
// public async Task<IReadOnlyList<uint>> GetIdsBySearchAsync(string search)
|
||||||
{
|
// {
|
||||||
using var http = GetHttpClient();
|
// using var http = GetHttpClient();
|
||||||
try
|
// try
|
||||||
{
|
// {
|
||||||
var url = $"https://nhentai.net/search/?q={Uri.EscapeDataString(search)}&sort=popular-today";
|
// var url = $"https://nhentai.net/search/?q={Uri.EscapeDataString(search)}&sort=popular-today";
|
||||||
var strRes = await http.GetStringAsync(url);
|
// var strRes = await http.GetStringAsync(url);
|
||||||
var doc = await _htmlParser.ParseDocumentAsync(strRes);
|
// var doc = await _htmlParser.ParseDocumentAsync(strRes);
|
||||||
|
//
|
||||||
var elems = doc.QuerySelectorAll(".container .gallery a")
|
// var elems = doc.QuerySelectorAll(".container .gallery a")
|
||||||
.Cast<IHtmlAnchorElement>()
|
// .Cast<IHtmlAnchorElement>()
|
||||||
.Where(x => x.PathName.StartsWith("/g/"))
|
// .Where(x => x.PathName.StartsWith("/g/"))
|
||||||
.Select(x => x.PathName[3..^1])
|
// .Select(x => x.PathName[3..^1])
|
||||||
.Select(uint.Parse)
|
// .Select(uint.Parse)
|
||||||
.ToArray();
|
// .ToArray();
|
||||||
|
//
|
||||||
return elems;
|
// return elems;
|
||||||
}
|
// }
|
||||||
catch (HttpRequestException)
|
// catch (HttpRequestException)
|
||||||
{
|
// {
|
||||||
Log.Warning("Nhentai search for {NhentaiSearch} failed", search);
|
// Log.Warning("Nhentai search for {NhentaiSearch} failed", search);
|
||||||
return Array.Empty<uint>();
|
// return Array.Empty<uint>();
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
@@ -360,67 +360,65 @@ public partial class NSFW : NadekoModule<ISearchImagesService>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[Cmd]
|
// [RequireNsfw(Group = "nsfw_or_dm")]
|
||||||
[RequireContext(ContextType.Guild)]
|
// [RequireContext(ContextType.DM, Group = "nsfw_or_dm")]
|
||||||
[RequireNsfw(Group = "nsfw_or_dm")]
|
// [Priority(1)]
|
||||||
[RequireContext(ContextType.DM, Group = "nsfw_or_dm")]
|
// public async Task Nhentai(uint id)
|
||||||
[Priority(1)]
|
// {
|
||||||
public async Task Nhentai(uint id)
|
// var g = await _service.GetNhentaiByIdAsync(id);
|
||||||
{
|
//
|
||||||
var g = await _service.GetNhentaiByIdAsync(id);
|
// if (g is null)
|
||||||
|
// {
|
||||||
if (g is null)
|
// await ReplyErrorLocalizedAsync(strs.not_found);
|
||||||
{
|
// return;
|
||||||
await ReplyErrorLocalizedAsync(strs.not_found);
|
// }
|
||||||
return;
|
//
|
||||||
}
|
// await SendNhentaiGalleryInternalAsync(g);
|
||||||
|
// }
|
||||||
await SendNhentaiGalleryInternalAsync(g);
|
//
|
||||||
}
|
// [Cmd]
|
||||||
|
// [RequireContext(ContextType.Guild)]
|
||||||
[Cmd]
|
// [RequireNsfw(Group = "nsfw_or_dm")]
|
||||||
[RequireContext(ContextType.Guild)]
|
// [RequireContext(ContextType.DM, Group = "nsfw_or_dm")]
|
||||||
[RequireNsfw(Group = "nsfw_or_dm")]
|
// [Priority(0)]
|
||||||
[RequireContext(ContextType.DM, Group = "nsfw_or_dm")]
|
// public async Task Nhentai([Leftover] string query)
|
||||||
[Priority(0)]
|
// {
|
||||||
public async Task Nhentai([Leftover] string query)
|
// var g = await _service.GetNhentaiBySearchAsync(query);
|
||||||
{
|
//
|
||||||
var g = await _service.GetNhentaiBySearchAsync(query);
|
// if (g is null)
|
||||||
|
// {
|
||||||
if (g is null)
|
// await ReplyErrorLocalizedAsync(strs.not_found);
|
||||||
{
|
// return;
|
||||||
await ReplyErrorLocalizedAsync(strs.not_found);
|
// }
|
||||||
return;
|
//
|
||||||
}
|
// await SendNhentaiGalleryInternalAsync(g);
|
||||||
|
// }
|
||||||
await SendNhentaiGalleryInternalAsync(g);
|
//
|
||||||
}
|
// private async Task SendNhentaiGalleryInternalAsync(Gallery g)
|
||||||
|
// {
|
||||||
private async Task SendNhentaiGalleryInternalAsync(Gallery g)
|
// var count = 0;
|
||||||
{
|
// var tagString = g.Tags.Shuffle()
|
||||||
var count = 0;
|
// .Select(tag => $"[{tag.Name}]({tag.Url})")
|
||||||
var tagString = g.Tags.Shuffle()
|
// .TakeWhile(tag => (count += tag.Length) < 1000)
|
||||||
.Select(tag => $"[{tag.Name}]({tag.Url})")
|
// .Join(" ");
|
||||||
.TakeWhile(tag => (count += tag.Length) < 1000)
|
//
|
||||||
.Join(" ");
|
// var embed = _eb.Create()
|
||||||
|
// .WithTitle(g.Title)
|
||||||
var embed = _eb.Create()
|
// .WithDescription(g.FullTitle)
|
||||||
.WithTitle(g.Title)
|
// .WithImageUrl(g.Thumbnail)
|
||||||
.WithDescription(g.FullTitle)
|
// .WithUrl(g.Url)
|
||||||
.WithImageUrl(g.Thumbnail)
|
// .AddField(GetText(strs.favorites), g.Likes, true)
|
||||||
.WithUrl(g.Url)
|
// .AddField(GetText(strs.pages), g.PageCount, true)
|
||||||
.AddField(GetText(strs.favorites), g.Likes, true)
|
// .AddField(GetText(strs.tags),
|
||||||
.AddField(GetText(strs.pages), g.PageCount, true)
|
// string.IsNullOrWhiteSpace(tagString)
|
||||||
.AddField(GetText(strs.tags),
|
// ? "?"
|
||||||
string.IsNullOrWhiteSpace(tagString)
|
// : tagString,
|
||||||
? "?"
|
// true)
|
||||||
: tagString,
|
// .WithFooter(g.UploadedAt.ToString("f"))
|
||||||
true)
|
// .WithOkColor();
|
||||||
.WithFooter(g.UploadedAt.ToString("f"))
|
//
|
||||||
.WithOkColor();
|
// await ctx.Channel.EmbedAsync(embed);
|
||||||
|
// }
|
||||||
await ctx.Channel.EmbedAsync(embed);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task InternalDapiCommand(
|
private async Task InternalDapiCommand(
|
||||||
string[] tags,
|
string[] tags,
|
||||||
|
@@ -19,17 +19,15 @@ public class SearchImagesService : ISearchImagesService, INService
|
|||||||
private readonly SearchImageCacher _cache;
|
private readonly SearchImageCacher _cache;
|
||||||
private readonly IHttpClientFactory _httpFactory;
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
private readonly DbService _db;
|
private readonly DbService _db;
|
||||||
private readonly INhentaiService _nh;
|
|
||||||
|
|
||||||
private readonly object _taglock = new();
|
private readonly object _taglock = new();
|
||||||
|
|
||||||
public SearchImagesService(
|
public SearchImagesService(
|
||||||
DbService db,
|
DbService db,
|
||||||
SearchImageCacher cacher,
|
SearchImageCacher cacher,
|
||||||
IHttpClientFactory httpFactory,
|
IHttpClientFactory httpFactory
|
||||||
INhentaiService nh)
|
)
|
||||||
{
|
{
|
||||||
_nh = nh;
|
|
||||||
_db = db;
|
_db = db;
|
||||||
_rng = new NadekoRandom();
|
_rng = new NadekoRandom();
|
||||||
_cache = cacher;
|
_cache = cacher;
|
||||||
@@ -277,6 +275,7 @@ public class SearchImagesService : ISearchImagesService, INService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
#region Nhentai
|
#region Nhentai
|
||||||
|
|
||||||
public Task<Gallery?> GetNhentaiByIdAsync(uint id)
|
public Task<Gallery?> GetNhentaiByIdAsync(uint id)
|
||||||
@@ -294,4 +293,5 @@ public class SearchImagesService : ISearchImagesService, INService
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
*/
|
||||||
}
|
}
|
@@ -85,11 +85,11 @@ public partial class Searches
|
|||||||
.WithUrl($"https://www.tradingview.com/chart/?symbol={stock.Symbol}")
|
.WithUrl($"https://www.tradingview.com/chart/?symbol={stock.Symbol}")
|
||||||
.WithTitle(stock.Name)
|
.WithTitle(stock.Name)
|
||||||
.AddField(GetText(strs.price), $"{sign} **{price}**", true)
|
.AddField(GetText(strs.price), $"{sign} **{price}**", true)
|
||||||
.AddField(GetText(strs.market_cap), stock.MarketCap.ToString("C0", localCulture), true)
|
.AddField(GetText(strs.market_cap), stock.MarketCap, true)
|
||||||
.AddField(GetText(strs.volume_24h), stock.DailyVolume.ToString("C0", localCulture), true)
|
.AddField(GetText(strs.volume_24h), stock.DailyVolume.ToString("C0", localCulture), true)
|
||||||
.AddField("Change", $"{change} ({changePercent})", true)
|
.AddField("Change", $"{change} ({changePercent})", true)
|
||||||
.AddField("Change 50d", $"{sign50}{change50}", true)
|
// .AddField("Change 50d", $"{sign50}{change50}", true)
|
||||||
.AddField("Change 200d", $"{sign200}{change200}", true)
|
// .AddField("Change 200d", $"{sign200}{change200}", true)
|
||||||
.WithFooter(stock.Exchange);
|
.WithFooter(stock.Exchange);
|
||||||
|
|
||||||
var message = await ctx.Channel.EmbedAsync(eb);
|
var message = await ctx.Channel.EmbedAsync(eb);
|
||||||
|
@@ -1,5 +1,8 @@
|
|||||||
using CsvHelper;
|
using AngleSharp;
|
||||||
|
using AngleSharp.Html.Dom;
|
||||||
|
using CsvHelper;
|
||||||
using CsvHelper.Configuration;
|
using CsvHelper.Configuration;
|
||||||
|
using CsvHelper.Configuration.Attributes;
|
||||||
using Google.Protobuf.WellKnownTypes;
|
using Google.Protobuf.WellKnownTypes;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
@@ -23,33 +26,61 @@ public sealed class DefaultStockDataService : IStockDataService, INService
|
|||||||
return default;
|
return default;
|
||||||
|
|
||||||
using var http = _httpClientFactory.CreateClient();
|
using var http = _httpClientFactory.CreateClient();
|
||||||
var data = await http.GetFromJsonAsync<YahooQueryModel>(
|
|
||||||
$"https://query1.finance.yahoo.com/v7/finance/quote?symbols={query}");
|
|
||||||
|
|
||||||
if (data is null)
|
|
||||||
return default;
|
|
||||||
|
|
||||||
var symbol = data.QuoteResponse.Result.FirstOrDefault();
|
|
||||||
|
|
||||||
if (symbol is null)
|
var quoteHtmlPage = $"https://finance.yahoo.com/quote/{query.ToUpperInvariant()}";
|
||||||
return default;
|
|
||||||
|
var config = Configuration.Default.WithDefaultLoader();
|
||||||
|
using var document = await BrowsingContext.New(config).OpenAsync(quoteHtmlPage);
|
||||||
|
var divElem =
|
||||||
|
document.QuerySelector(
|
||||||
|
"#quote-header-info > div:nth-child(2) > div > div > h1");
|
||||||
|
var tickerName = (divElem)?.TextContent;
|
||||||
|
|
||||||
|
var marketcap = document
|
||||||
|
.QuerySelectorAll("table")
|
||||||
|
.Skip(1)
|
||||||
|
.First()
|
||||||
|
.QuerySelector("tbody > tr > td:nth-child(2)")
|
||||||
|
?.TextContent;
|
||||||
|
|
||||||
|
|
||||||
|
var volume = document.QuerySelector("td[data-test='AVERAGE_VOLUME_3MONTH-value']")
|
||||||
|
?.TextContent;
|
||||||
|
|
||||||
|
var close= document.QuerySelector("td[data-test='PREV_CLOSE-value']")
|
||||||
|
?.TextContent ?? "0";
|
||||||
|
|
||||||
|
var price = document
|
||||||
|
.QuerySelector("#quote-header-info")
|
||||||
|
?.QuerySelector("fin-streamer[data-field='regularMarketPrice']")
|
||||||
|
?.TextContent ?? close;
|
||||||
|
|
||||||
|
// var data = await http.GetFromJsonAsync<YahooQueryModel>(
|
||||||
|
// $"https://query1.finance.yahoo.com/v7/finance/quote?symbols={query}");
|
||||||
|
//
|
||||||
|
// if (data is null)
|
||||||
|
// return default;
|
||||||
|
|
||||||
|
// var symbol = data.QuoteResponse.Result.FirstOrDefault();
|
||||||
|
|
||||||
|
// if (symbol is null)
|
||||||
|
// return default;
|
||||||
|
|
||||||
return new()
|
return new()
|
||||||
{
|
{
|
||||||
Name = symbol.LongName,
|
Name = tickerName,
|
||||||
Symbol = symbol.Symbol,
|
Symbol = query,
|
||||||
Price = symbol.RegularMarketPrice,
|
Price = double.Parse(price, NumberStyles.Any, CultureInfo.InvariantCulture),
|
||||||
Close = symbol.RegularMarketPreviousClose,
|
Close = double.Parse(close, NumberStyles.Any, CultureInfo.InvariantCulture),
|
||||||
MarketCap = symbol.MarketCap,
|
MarketCap = marketcap,
|
||||||
Change50d = symbol.FiftyDayAverageChangePercent,
|
DailyVolume = (long)double.Parse(volume ?? "0", NumberStyles.Any, CultureInfo.InvariantCulture),
|
||||||
Change200d = symbol.TwoHundredDayAverageChangePercent,
|
|
||||||
DailyVolume = symbol.AverageDailyVolume10Day,
|
|
||||||
Exchange = symbol.FullExchangeName
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
// Log.Warning(ex, "Error getting stock data: {ErrorMessage}", ex.Message);
|
Log.Warning(ex, "Error getting stock data: {ErrorMessage}", ex.ToString());
|
||||||
return default;
|
return default;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,9 +105,9 @@ public sealed class DefaultStockDataService : IStockDataService, INService
|
|||||||
return Array.Empty<SymbolData>();
|
return Array.Empty<SymbolData>();
|
||||||
|
|
||||||
return data.Items
|
return data.Items
|
||||||
.Where(x => x.Type == "S")
|
.Where(x => x.Type == "S")
|
||||||
.Select(x => new SymbolData(x.Symbol, x.Name))
|
.Select(x => new SymbolData(x.Symbol, x.Name))
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static CsvConfiguration _csvConfig = new(CultureInfo.InvariantCulture)
|
private static CsvConfiguration _csvConfig = new(CultureInfo.InvariantCulture)
|
||||||
|
@@ -6,7 +6,7 @@ public class StockData
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
public string Symbol { get; set; }
|
public string Symbol { get; set; }
|
||||||
public double Price { get; set; }
|
public double Price { get; set; }
|
||||||
public long MarketCap { get; set; }
|
public string MarketCap { get; set; }
|
||||||
public double Close { get; set; }
|
public double Close { get; set; }
|
||||||
public double Change50d { get; set; }
|
public double Change50d { get; set; }
|
||||||
public double Change200d { get; set; }
|
public double Change200d { get; set; }
|
||||||
|
@@ -39,7 +39,7 @@ public partial class Searches
|
|||||||
[Cmd]
|
[Cmd]
|
||||||
public async Task MagicItem()
|
public async Task MagicItem()
|
||||||
{
|
{
|
||||||
if (!_service.WowJokes.Any())
|
if (!_service.MagicItems.Any())
|
||||||
{
|
{
|
||||||
await ReplyErrorLocalizedAsync(strs.magicitems_not_loaded);
|
await ReplyErrorLocalizedAsync(strs.magicitems_not_loaded);
|
||||||
return;
|
return;
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
#nullable disable
|
#nullable disable
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
using NadekoBot.Modules.Administration.Services;
|
using NadekoBot.Modules.Administration.Services;
|
||||||
using NadekoBot.Modules.Searches.Common;
|
using NadekoBot.Modules.Searches.Common;
|
||||||
@@ -199,7 +199,7 @@ public partial class Searches : NadekoModule<SearchesService>
|
|||||||
if (!await ValidateQuery(ffs))
|
if (!await ValidateQuery(ffs))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var shortenedUrl = await _google.ShortenUrl($"https://lmgtfy.com/?q={Uri.EscapeDataString(ffs)}");
|
var shortenedUrl = await _google.ShortenUrl($"https://letmegooglethat.com/?q={Uri.EscapeDataString(ffs)}");
|
||||||
await SendConfirmAsync($"<{shortenedUrl}>");
|
await SendConfirmAsync($"<{shortenedUrl}>");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +325,7 @@ public partial class Searches : NadekoModule<SearchesService>
|
|||||||
return _eb.Create()
|
return _eb.Create()
|
||||||
.WithOkColor()
|
.WithOkColor()
|
||||||
.WithUrl(item.Permalink)
|
.WithUrl(item.Permalink)
|
||||||
.WithAuthor(item.Word)
|
.WithTitle(item.Word)
|
||||||
.WithDescription(item.Definition);
|
.WithDescription(item.Definition);
|
||||||
},
|
},
|
||||||
items.Length,
|
items.Length,
|
||||||
@@ -422,30 +422,6 @@ public partial class Searches : NadekoModule<SearchesService>
|
|||||||
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact);
|
await SendConfirmAsync("🐈" + GetText(strs.catfact), fact);
|
||||||
}
|
}
|
||||||
|
|
||||||
//done in 3.0
|
|
||||||
[Cmd]
|
|
||||||
[RequireContext(ContextType.Guild)]
|
|
||||||
public async Task Revav([Leftover] IGuildUser usr = null)
|
|
||||||
{
|
|
||||||
if (usr is null)
|
|
||||||
usr = (IGuildUser)ctx.User;
|
|
||||||
|
|
||||||
var av = usr.RealAvatarUrl();
|
|
||||||
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}");
|
|
||||||
}
|
|
||||||
|
|
||||||
//done in 3.0
|
|
||||||
[Cmd]
|
|
||||||
public async Task Revimg([Leftover] string imageLink = null)
|
|
||||||
{
|
|
||||||
imageLink = imageLink?.Trim() ?? "";
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(imageLink))
|
|
||||||
return;
|
|
||||||
|
|
||||||
await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
public async Task Wiki([Leftover] string query = null)
|
public async Task Wiki([Leftover] string query = null)
|
||||||
{
|
{
|
||||||
|
@@ -9,6 +9,9 @@ using SixLabors.ImageSharp;
|
|||||||
using SixLabors.ImageSharp.Drawing.Processing;
|
using SixLabors.ImageSharp.Drawing.Processing;
|
||||||
using SixLabors.ImageSharp.PixelFormats;
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
using SixLabors.ImageSharp.Processing;
|
using SixLabors.ImageSharp.Processing;
|
||||||
|
using System.Collections;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
using Color = SixLabors.ImageSharp.Color;
|
using Color = SixLabors.ImageSharp.Color;
|
||||||
using Image = SixLabors.ImageSharp.Image;
|
using Image = SixLabors.ImageSharp.Image;
|
||||||
|
|
||||||
@@ -296,8 +299,8 @@ public class SearchesService : INService
|
|||||||
public async Task<string> GetChuckNorrisJoke()
|
public async Task<string> GetChuckNorrisJoke()
|
||||||
{
|
{
|
||||||
using var http = _httpFactory.CreateClient();
|
using var http = _httpFactory.CreateClient();
|
||||||
var response = await http.GetStringAsync(new Uri("http://api.icndb.com/jokes/random/"));
|
var response = await http.GetStringAsync(new Uri("https://api.chucknorris.io/jokes/random"));
|
||||||
return JObject.Parse(response)["value"]["joke"] + " 😆";
|
return JObject.Parse(response)["value"] + " 😆";
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<MtgData> GetMtgCardAsync(string search)
|
public async Task<MtgData> GetMtgCardAsync(string search)
|
||||||
|
@@ -28,6 +28,7 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
|
|
||||||
private readonly IPubSub _pubSub;
|
private readonly IPubSub _pubSub;
|
||||||
private readonly IEmbedBuilderService _eb;
|
private readonly IEmbedBuilderService _eb;
|
||||||
|
private readonly SearchesConfigService _config;
|
||||||
|
|
||||||
public TypedKey<List<StreamData>> StreamsOnlineKey { get; }
|
public TypedKey<List<StreamData>> StreamsOnlineKey { get; }
|
||||||
public TypedKey<List<StreamData>> StreamsOfflineKey { get; }
|
public TypedKey<List<StreamData>> StreamsOfflineKey { get; }
|
||||||
@@ -49,13 +50,15 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
IHttpClientFactory httpFactory,
|
IHttpClientFactory httpFactory,
|
||||||
Bot bot,
|
Bot bot,
|
||||||
IPubSub pubSub,
|
IPubSub pubSub,
|
||||||
IEmbedBuilderService eb)
|
IEmbedBuilderService eb,
|
||||||
|
SearchesConfigService config)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
_client = client;
|
_client = client;
|
||||||
_strings = strings;
|
_strings = strings;
|
||||||
_pubSub = pubSub;
|
_pubSub = pubSub;
|
||||||
_eb = eb;
|
_eb = eb;
|
||||||
|
_config = config;
|
||||||
|
|
||||||
_streamTracker = new(httpFactory, creds);
|
_streamTracker = new(httpFactory, creds);
|
||||||
|
|
||||||
@@ -69,34 +72,34 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
{
|
{
|
||||||
var ids = client.GetGuildIds();
|
var ids = client.GetGuildIds();
|
||||||
var guildConfigs = uow.Set<GuildConfig>()
|
var guildConfigs = uow.Set<GuildConfig>()
|
||||||
.AsQueryable()
|
.AsQueryable()
|
||||||
.Include(x => x.FollowedStreams)
|
.Include(x => x.FollowedStreams)
|
||||||
.Where(x => ids.Contains(x.GuildId))
|
.Where(x => ids.Contains(x.GuildId))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
_offlineNotificationServers = new(guildConfigs
|
_offlineNotificationServers = new(guildConfigs
|
||||||
.Where(gc => gc.NotifyStreamOffline)
|
.Where(gc => gc.NotifyStreamOffline)
|
||||||
.Select(x => x.GuildId)
|
.Select(x => x.GuildId)
|
||||||
.ToList());
|
.ToList());
|
||||||
|
|
||||||
_deleteOnOfflineServers = new(guildConfigs
|
_deleteOnOfflineServers = new(guildConfigs
|
||||||
.Where(gc => gc.DeleteStreamOnlineMessage)
|
.Where(gc => gc.DeleteStreamOnlineMessage)
|
||||||
.Select(x => x.GuildId)
|
.Select(x => x.GuildId)
|
||||||
.ToList());
|
.ToList());
|
||||||
|
|
||||||
var followedStreams = guildConfigs.SelectMany(x => x.FollowedStreams).ToList();
|
var followedStreams = guildConfigs.SelectMany(x => x.FollowedStreams).ToList();
|
||||||
|
|
||||||
_shardTrackedStreams = followedStreams.GroupBy(x => new
|
_shardTrackedStreams = followedStreams.GroupBy(x => new
|
||||||
{
|
{
|
||||||
x.Type,
|
x.Type,
|
||||||
Name = x.Username.ToLower()
|
Name = x.Username.ToLower()
|
||||||
})
|
})
|
||||||
.ToList()
|
.ToList()
|
||||||
.ToDictionary(
|
.ToDictionary(
|
||||||
x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()),
|
x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()),
|
||||||
x => x.GroupBy(y => y.GuildId)
|
x => x.GroupBy(y => y.GuildId)
|
||||||
.ToDictionary(y => y.Key,
|
.ToDictionary(y => y.Key,
|
||||||
y => y.AsEnumerable().ToHashSet()));
|
y => y.AsEnumerable().ToHashSet()));
|
||||||
|
|
||||||
// shard 0 will keep track of when there are no more guilds which track a stream
|
// shard 0 will keep track of when there are no more guilds which track a stream
|
||||||
if (client.ShardId == 0)
|
if (client.ShardId == 0)
|
||||||
@@ -107,12 +110,12 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
_streamTracker.AddLastData(fs.CreateKey(), null, false);
|
_streamTracker.AddLastData(fs.CreateKey(), null, false);
|
||||||
|
|
||||||
_trackCounter = allFollowedStreams.GroupBy(x => new
|
_trackCounter = allFollowedStreams.GroupBy(x => new
|
||||||
{
|
{
|
||||||
x.Type,
|
x.Type,
|
||||||
Name = x.Username.ToLower()
|
Name = x.Username.ToLower()
|
||||||
})
|
})
|
||||||
.ToDictionary(x => new StreamDataKey(x.Key.Type, x.Key.Name),
|
.ToDictionary(x => new StreamDataKey(x.Key.Type, x.Key.Name),
|
||||||
x => x.Select(fs => fs.GuildId).ToHashSet());
|
x => x.Select(fs => fs.GuildId).ToHashSet());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +155,7 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
var deleteGroups = failingStreams.GroupBy(x => x.Type)
|
var deleteGroups = failingStreams.GroupBy(x => x.Type)
|
||||||
.ToDictionary(x => x.Key, x => x.Select(y => y.Name).ToList());
|
.ToDictionary(x => x.Key, x => x.Select(y => y.Name).ToList());
|
||||||
|
|
||||||
await using var uow = _db.GetDbContext();
|
await using var uow = _db.GetDbContext();
|
||||||
foreach (var kvp in deleteGroups)
|
foreach (var kvp in deleteGroups)
|
||||||
@@ -165,9 +168,9 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
string.Join(", ", kvp.Value));
|
string.Join(", ", kvp.Value));
|
||||||
|
|
||||||
var toDelete = uow.Set<FollowedStream>()
|
var toDelete = uow.Set<FollowedStream>()
|
||||||
.AsQueryable()
|
.AsQueryable()
|
||||||
.Where(x => x.Type == kvp.Key && kvp.Value.Contains(x.Username))
|
.Where(x => x.Type == kvp.Key && kvp.Value.Contains(x.Username))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
uow.RemoveRange(toDelete);
|
uow.RemoveRange(toDelete);
|
||||||
await uow.SaveChangesAsync();
|
await uow.SaveChangesAsync();
|
||||||
@@ -246,13 +249,13 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
if (_shardTrackedStreams.TryGetValue(key, out var fss))
|
if (_shardTrackedStreams.TryGetValue(key, out var fss))
|
||||||
{
|
{
|
||||||
await fss
|
await fss
|
||||||
// send offline stream notifications only to guilds which enable it with .stoff
|
// send offline stream notifications only to guilds which enable it with .stoff
|
||||||
.SelectMany(x => x.Value)
|
.SelectMany(x => x.Value)
|
||||||
.Where(x => _offlineNotificationServers.Contains(x.GuildId))
|
.Where(x => _offlineNotificationServers.Contains(x.GuildId))
|
||||||
.Select(fs => _client.GetGuild(fs.GuildId)
|
.Select(fs => _client.GetGuild(fs.GuildId)
|
||||||
?.GetTextChannel(fs.ChannelId)
|
?.GetTextChannel(fs.ChannelId)
|
||||||
?.EmbedAsync(GetEmbed(fs.GuildId, stream)))
|
?.EmbedAsync(GetEmbed(fs.GuildId, stream)))
|
||||||
.WhenAll();
|
.WhenAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,28 +269,28 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
if (_shardTrackedStreams.TryGetValue(key, out var fss))
|
if (_shardTrackedStreams.TryGetValue(key, out var fss))
|
||||||
{
|
{
|
||||||
var messages = await fss.SelectMany(x => x.Value)
|
var messages = await fss.SelectMany(x => x.Value)
|
||||||
.Select(async fs =>
|
.Select(async fs =>
|
||||||
{
|
{
|
||||||
var textChannel = _client.GetGuild(fs.GuildId)?.GetTextChannel(fs.ChannelId);
|
var textChannel = _client.GetGuild(fs.GuildId)?.GetTextChannel(fs.ChannelId);
|
||||||
|
|
||||||
if (textChannel is null)
|
if (textChannel is null)
|
||||||
return default;
|
return default;
|
||||||
|
|
||||||
var rep = new ReplacementBuilder().WithOverride("%user%", () => fs.Username)
|
var rep = new ReplacementBuilder().WithOverride("%user%", () => fs.Username)
|
||||||
.WithOverride("%platform%", () => fs.Type.ToString())
|
.WithOverride("%platform%", () => fs.Type.ToString())
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var message = string.IsNullOrWhiteSpace(fs.Message) ? "" : rep.Replace(fs.Message);
|
var message = string.IsNullOrWhiteSpace(fs.Message) ? "" : rep.Replace(fs.Message);
|
||||||
|
|
||||||
var msg = await textChannel.EmbedAsync(GetEmbed(fs.GuildId, stream, false), message);
|
var msg = await textChannel.EmbedAsync(GetEmbed(fs.GuildId, stream, false), message);
|
||||||
|
|
||||||
// only cache the ids of channel/message pairs
|
// only cache the ids of channel/message pairs
|
||||||
if(_deleteOnOfflineServers.Contains(fs.GuildId))
|
if (_deleteOnOfflineServers.Contains(fs.GuildId))
|
||||||
return (textChannel.Id, msg.Id);
|
return (textChannel.Id, msg.Id);
|
||||||
else
|
else
|
||||||
return default;
|
return default;
|
||||||
})
|
})
|
||||||
.WhenAll();
|
.WhenAll();
|
||||||
|
|
||||||
|
|
||||||
// push online stream messages to redis
|
// push online stream messages to redis
|
||||||
@@ -297,16 +300,15 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var pairs = messages
|
var pairs = messages
|
||||||
.Where(x => x != default)
|
.Where(x => x != default)
|
||||||
.Select(x => (x.Item1, x.Item2))
|
.Select(x => (x.Item1, x.Item2))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
if (pairs.Count > 0)
|
if (pairs.Count > 0)
|
||||||
await OnlineMessagesSent(key.Type, key.Name, pairs);
|
await OnlineMessagesSent(key.Type, key.Name, pairs);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -384,10 +386,10 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
await using (var uow = _db.GetDbContext())
|
await using (var uow = _db.GetDbContext())
|
||||||
{
|
{
|
||||||
var fss = uow.Set<FollowedStream>()
|
var fss = uow.Set<FollowedStream>()
|
||||||
.AsQueryable()
|
.AsQueryable()
|
||||||
.Where(x => x.GuildId == guildId)
|
.Where(x => x.GuildId == guildId)
|
||||||
.OrderBy(x => x.Id)
|
.OrderBy(x => x.Id)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
// out of range
|
// out of range
|
||||||
if (fss.Count <= index)
|
if (fss.Count <= index)
|
||||||
@@ -450,7 +452,9 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
GuildId = guildId
|
GuildId = guildId
|
||||||
};
|
};
|
||||||
|
|
||||||
if (gc.FollowedStreams.Count >= 10)
|
var config = _config.Data;
|
||||||
|
if (config.FollowedStreams.MaxCount is not -1
|
||||||
|
&& gc.FollowedStreams.Count >= config.FollowedStreams.MaxCount)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
gc.FollowedStreams.Add(fs);
|
gc.FollowedStreams.Add(fs);
|
||||||
@@ -475,10 +479,10 @@ public sealed class StreamNotificationService : INService, IReadyExecutor
|
|||||||
public IEmbedBuilder GetEmbed(ulong guildId, StreamData status, bool showViewers = true)
|
public IEmbedBuilder GetEmbed(ulong guildId, StreamData status, bool showViewers = true)
|
||||||
{
|
{
|
||||||
var embed = _eb.Create()
|
var embed = _eb.Create()
|
||||||
.WithTitle(status.Name)
|
.WithTitle(status.Name)
|
||||||
.WithUrl(status.StreamUrl)
|
.WithUrl(status.StreamUrl)
|
||||||
.WithDescription(status.StreamUrl)
|
.WithDescription(status.StreamUrl)
|
||||||
.AddField(GetText(guildId, strs.status), status.IsLive ? "🟢 Online" : "🔴 Offline", true);
|
.AddField(GetText(guildId, strs.status), status.IsLive ? "🟢 Online" : "🔴 Offline", true);
|
||||||
|
|
||||||
if (showViewers)
|
if (showViewers)
|
||||||
{
|
{
|
||||||
|
@@ -30,7 +30,7 @@ public partial class SearchesConfig : ICloneable<SearchesConfig>
|
|||||||
- `ytdlp` - recommended easy, uses `yt-dlp`. Requires `yt-dlp` to be installed and it's path added to env variables
|
- `ytdlp` - recommended easy, uses `yt-dlp`. Requires `yt-dlp` to be installed and it's path added to env variables
|
||||||
|
|
||||||
- `invidious` - recommended advanced, uses invidious api. Requires at least one invidious instance specified in the `invidiousInstances` property")]
|
- `invidious` - recommended advanced, uses invidious api. Requires at least one invidious instance specified in the `invidiousInstances` property")]
|
||||||
public YoutubeSearcher YtProvider { get; set; } = YoutubeSearcher.Ytdl;
|
public YoutubeSearcher YtProvider { get; set; } = YoutubeSearcher.Ytdlp;
|
||||||
|
|
||||||
[Comment(@"Set the searx instance urls in case you want to use 'searx' for either img or web search.
|
[Comment(@"Set the searx instance urls in case you want to use 'searx' for either img or web search.
|
||||||
Nadeko will use a random one for each request.
|
Nadeko will use a random one for each request.
|
||||||
@@ -55,6 +55,15 @@ Use a fully qualified url. Example: https://my-invidious-instance.mydomain.com
|
|||||||
Instances specified must have api available.
|
Instances specified must have api available.
|
||||||
You check that by opening an api endpoint in your browser. For example: https://my-invidious-instance.mydomain.com/api/v1/trending")]
|
You check that by opening an api endpoint in your browser. For example: https://my-invidious-instance.mydomain.com/api/v1/trending")]
|
||||||
public List<string> InvidiousInstances { get; set; } = new List<string>();
|
public List<string> InvidiousInstances { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
[Comment("Maximum number of followed streams per server")]
|
||||||
|
public FollowedStreamConfig FollowedStreams { get; set; } = new FollowedStreamConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class FollowedStreamConfig
|
||||||
|
{
|
||||||
|
[Comment("Maximum number of streams that each server can follow. -1 for infinite")]
|
||||||
|
public int MaxCount { get; set; } = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum YoutubeSearcher
|
public enum YoutubeSearcher
|
||||||
|
@@ -28,6 +28,11 @@ public class SearchesConfigService : ConfigServiceBase<SearchesConfig>
|
|||||||
ConfigParsers.InsensitiveEnum,
|
ConfigParsers.InsensitiveEnum,
|
||||||
ConfigPrinters.ToString);
|
ConfigPrinters.ToString);
|
||||||
|
|
||||||
|
AddParsedProp("followedStreams.maxCount",
|
||||||
|
sc => sc.FollowedStreams.MaxCount,
|
||||||
|
int.TryParse,
|
||||||
|
ConfigPrinters.ToString);
|
||||||
|
|
||||||
Migrate();
|
Migrate();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,5 +46,13 @@ public class SearchesConfigService : ConfigServiceBase<SearchesConfig>
|
|||||||
c.WebSearchEngine = WebSearchEngine.Google_Scrape;
|
c.WebSearchEngine = WebSearchEngine.Google_Scrape;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.Version < 2)
|
||||||
|
{
|
||||||
|
ModifyConfig(c =>
|
||||||
|
{
|
||||||
|
c.Version = 2;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -127,14 +127,26 @@ public partial class Utility
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async Task ShowQuoteData(Quote data)
|
private async Task ShowQuoteData(Quote data)
|
||||||
=> await ctx.Channel.EmbedAsync(_eb.Create(ctx)
|
{
|
||||||
.WithOkColor()
|
var eb = _eb.Create(ctx)
|
||||||
.WithTitle(GetText(strs.quote_id($"#{data.Id}")))
|
.WithOkColor()
|
||||||
.AddField(GetText(strs.trigger), data.Keyword)
|
.WithTitle($"{GetText(strs.quote_id($"#{data.Id}"))} | {GetText(strs.response)}:")
|
||||||
.AddField(GetText(strs.response),
|
.WithDescription(Format.Sanitize(data.Text).Replace("](", "]\\(").TrimTo(4096))
|
||||||
Format.Sanitize(data.Text).Replace("](", "]\\("))
|
.AddField(GetText(strs.trigger), data.Keyword)
|
||||||
.WithFooter(
|
.WithFooter(
|
||||||
GetText(strs.created_by($"{data.AuthorName} ({data.AuthorId})"))));
|
GetText(strs.created_by($"{data.AuthorName} ({data.AuthorId})")))
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
if (!(data.Text.Length > 4096))
|
||||||
|
{
|
||||||
|
await ctx.Channel.SendMessageAsync(embed: eb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.Channel.SendFileAsync(
|
||||||
|
attachment: new FileAttachment(await data.Text.ToStream(), "quote.txt"),
|
||||||
|
embed: eb);
|
||||||
|
}
|
||||||
|
|
||||||
private async Task QuoteSearchinternalAsync(string? keyword, string textOrAuthor)
|
private async Task QuoteSearchinternalAsync(string? keyword, string textOrAuthor)
|
||||||
{
|
{
|
||||||
|
@@ -94,7 +94,7 @@ public partial class Utility : NadekoModule
|
|||||||
|
|
||||||
var rng = new NadekoRandom();
|
var rng = new NadekoRandom();
|
||||||
var arr = await Task.Run(() => socketGuild.Users
|
var arr = await Task.Run(() => socketGuild.Users
|
||||||
.Where(u => u.Activities.FirstOrDefault()?.Name?.ToUpperInvariant()
|
.Where(u => u.Activities.FirstOrDefault()?.Name?.Trim().ToUpperInvariant()
|
||||||
== game)
|
== game)
|
||||||
.Select(u => u.Username)
|
.Select(u => u.Username)
|
||||||
.OrderBy(_ => rng.Next())
|
.OrderBy(_ => rng.Next())
|
||||||
@@ -465,11 +465,13 @@ public partial class Utility : NadekoModule
|
|||||||
if (tags.Length == 0)
|
if (tags.Length == 0)
|
||||||
tags = new[] { name };
|
tags = new[] { name };
|
||||||
|
|
||||||
await ctx.Guild.CreateStickerAsync(name,
|
await ctx.Guild.CreateStickerAsync(
|
||||||
string.IsNullOrWhiteSpace(description) ? "Missing description" : description,
|
name,
|
||||||
tags,
|
|
||||||
stream,
|
stream,
|
||||||
$"{name}.{format}");
|
$"{name}.{format}",
|
||||||
|
tags,
|
||||||
|
string.IsNullOrWhiteSpace(description) ? "Missing description" : description
|
||||||
|
);
|
||||||
|
|
||||||
await ctx.OkAsync();
|
await ctx.OkAsync();
|
||||||
}
|
}
|
||||||
@@ -550,15 +552,20 @@ public partial class Utility : NadekoModule
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var embed = msg.Embeds.FirstOrDefault();
|
if (!msg.Embeds.Any())
|
||||||
if (embed is null)
|
|
||||||
{
|
{
|
||||||
await ReplyErrorLocalizedAsync(strs.not_found);
|
await ReplyErrorLocalizedAsync(strs.not_found);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var json = SmartEmbedText.FromEmbed(embed, msg.Content).ToJson(_showEmbedSerializerOptions);
|
var json = new SmartEmbedTextArray()
|
||||||
await SendConfirmAsync(Format.Sanitize(json).Replace("](", "]\\("));
|
{
|
||||||
|
Content = msg.Content,
|
||||||
|
Embeds = msg.Embeds
|
||||||
|
.Map(x => new SmartEmbedArrayElementText(x))
|
||||||
|
}.ToJson(_showEmbedSerializerOptions);
|
||||||
|
|
||||||
|
await SendConfirmAsync(Format.Code(json, "json").Replace("](", "]\\("));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
|
@@ -259,8 +259,8 @@ public partial class Xp
|
|||||||
await ReplyConfirmLocalizedAsync(strs.club_applied(Format.Bold(club.ToString())));
|
await ReplyConfirmLocalizedAsync(strs.club_applied(Format.Bold(club.ToString())));
|
||||||
else if (result == ClubApplyResult.Banned)
|
else if (result == ClubApplyResult.Banned)
|
||||||
await ReplyErrorLocalizedAsync(strs.club_join_banned);
|
await ReplyErrorLocalizedAsync(strs.club_join_banned);
|
||||||
else if (result == ClubApplyResult.InsufficientLevel)
|
else if (result == ClubApplyResult.AlreadyApplied)
|
||||||
await ReplyErrorLocalizedAsync(strs.club_insuff_lvl);
|
await ReplyErrorLocalizedAsync(strs.club_already_applied);
|
||||||
else if (result == ClubApplyResult.AlreadyInAClub)
|
else if (result == ClubApplyResult.AlreadyInAClub)
|
||||||
await ReplyErrorLocalizedAsync(strs.club_already_in);
|
await ReplyErrorLocalizedAsync(strs.club_already_in);
|
||||||
}
|
}
|
||||||
@@ -283,6 +283,24 @@ public partial class Xp
|
|||||||
await ReplyErrorLocalizedAsync(strs.club_admin_perms);
|
await ReplyErrorLocalizedAsync(strs.club_admin_perms);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[Priority(1)]
|
||||||
|
public Task ClubReject(IUser user)
|
||||||
|
=> ClubReject(user.ToString());
|
||||||
|
|
||||||
|
[Cmd]
|
||||||
|
[Priority(0)]
|
||||||
|
public async Task ClubReject([Leftover] string userName)
|
||||||
|
{
|
||||||
|
var result = _service.RejectApplication(ctx.User.Id, userName, out var discordUser);
|
||||||
|
if (result == ClubDenyResult.Rejected)
|
||||||
|
await ReplyConfirmLocalizedAsync(strs.club_rejected(Format.Bold(discordUser.ToString())));
|
||||||
|
else if(result == ClubDenyResult.NoSuchApplicant)
|
||||||
|
await ReplyErrorLocalizedAsync(strs.club_accept_invalid_applicant);
|
||||||
|
else if(result == ClubDenyResult.NotOwnerOrAdmin)
|
||||||
|
await ReplyErrorLocalizedAsync(strs.club_admin_perms);
|
||||||
|
}
|
||||||
|
|
||||||
[Cmd]
|
[Cmd]
|
||||||
public async Task ClubLeave()
|
public async Task ClubLeave()
|
||||||
{
|
{
|
||||||
|
@@ -19,7 +19,6 @@ public class ClubService : INService, IClubService
|
|||||||
_httpFactory = httpFactory;
|
_httpFactory = httpFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<ClubCreateResult> CreateClubAsync(IUser user, string clubName)
|
public async Task<ClubCreateResult> CreateClubAsync(IUser user, string clubName)
|
||||||
{
|
{
|
||||||
//must be lvl 5 and must not be in a club already
|
//must be lvl 5 and must not be in a club already
|
||||||
@@ -140,14 +139,14 @@ public class ClubService : INService, IClubService
|
|||||||
|
|
||||||
//user banned or a member of a club, or already applied,
|
//user banned or a member of a club, or already applied,
|
||||||
// or doesn't min minumum level requirement, can't apply
|
// or doesn't min minumum level requirement, can't apply
|
||||||
if (du.Club is not null)
|
if (du.ClubId is not null)
|
||||||
return ClubApplyResult.AlreadyInAClub;
|
return ClubApplyResult.AlreadyInAClub;
|
||||||
|
|
||||||
if (club.Bans.Any(x => x.UserId == du.Id))
|
if (club.Bans.Any(x => x.UserId == du.Id))
|
||||||
return ClubApplyResult.Banned;
|
return ClubApplyResult.Banned;
|
||||||
|
|
||||||
if (club.Applicants.Any(x => x.UserId == du.Id))
|
if (club.Applicants.Any(x => x.UserId == du.Id))
|
||||||
return ClubApplyResult.InsufficientLevel;
|
return ClubApplyResult.AlreadyApplied;
|
||||||
|
|
||||||
var app = new ClubApplicants
|
var app = new ClubApplicants
|
||||||
{
|
{
|
||||||
@@ -187,6 +186,26 @@ public class ClubService : INService, IClubService
|
|||||||
return ClubAcceptResult.Accepted;
|
return ClubAcceptResult.Accepted;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ClubDenyResult RejectApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser)
|
||||||
|
{
|
||||||
|
discordUser = null;
|
||||||
|
using var uow = _db.GetDbContext();
|
||||||
|
var club = uow.Clubs.GetByOwnerOrAdmin(clubOwnerUserId);
|
||||||
|
if (club is null)
|
||||||
|
return ClubDenyResult.NotOwnerOrAdmin;
|
||||||
|
|
||||||
|
var applicant =
|
||||||
|
club.Applicants.FirstOrDefault(x => x.User.ToString().ToUpperInvariant() == userName.ToUpperInvariant());
|
||||||
|
if (applicant is null)
|
||||||
|
return ClubDenyResult.NoSuchApplicant;
|
||||||
|
|
||||||
|
club.Applicants.Remove(applicant);
|
||||||
|
|
||||||
|
discordUser = applicant.User;
|
||||||
|
uow.SaveChanges();
|
||||||
|
return ClubDenyResult.Rejected;
|
||||||
|
}
|
||||||
|
|
||||||
public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId)
|
public ClubInfo GetClubWithBansAndApplications(ulong ownerUserId)
|
||||||
{
|
{
|
||||||
using var uow = _db.GetDbContext();
|
using var uow = _db.GetDbContext();
|
||||||
|
@@ -13,6 +13,7 @@ public interface IClubService
|
|||||||
bool GetClubByName(string clubName, out ClubInfo club);
|
bool GetClubByName(string clubName, out ClubInfo club);
|
||||||
ClubApplyResult ApplyToClub(IUser user, ClubInfo club);
|
ClubApplyResult ApplyToClub(IUser user, ClubInfo club);
|
||||||
ClubAcceptResult AcceptApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser);
|
ClubAcceptResult AcceptApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser);
|
||||||
|
ClubDenyResult RejectApplication(ulong clubOwnerUserId, string userName, out DiscordUser discordUser);
|
||||||
ClubInfo? GetClubWithBansAndApplications(ulong ownerUserId);
|
ClubInfo? GetClubWithBansAndApplications(ulong ownerUserId);
|
||||||
ClubLeaveResult LeaveClub(IUser user);
|
ClubLeaveResult LeaveClub(IUser user);
|
||||||
bool SetDescription(ulong userId, string? desc);
|
bool SetDescription(ulong userId, string? desc);
|
||||||
@@ -26,8 +27,7 @@ public interface IClubService
|
|||||||
public enum ClubApplyResult
|
public enum ClubApplyResult
|
||||||
{
|
{
|
||||||
Success,
|
Success,
|
||||||
|
|
||||||
AlreadyInAClub,
|
AlreadyInAClub,
|
||||||
Banned,
|
Banned,
|
||||||
InsufficientLevel
|
AlreadyApplied
|
||||||
}
|
}
|
@@ -6,3 +6,10 @@ public enum ClubAcceptResult
|
|||||||
NotOwnerOrAdmin,
|
NotOwnerOrAdmin,
|
||||||
NoSuchApplicant,
|
NoSuchApplicant,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public enum ClubDenyResult
|
||||||
|
{
|
||||||
|
Rejected,
|
||||||
|
NoSuchApplicant,
|
||||||
|
NotOwnerOrAdmin
|
||||||
|
}
|
@@ -27,10 +27,10 @@
|
|||||||
<PackageReference Include="CodeHollow.FeedReader" Version="1.2.4" />
|
<PackageReference Include="CodeHollow.FeedReader" Version="1.2.4" />
|
||||||
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
||||||
<PackageReference Include="CsvHelper" Version="28.0.1" />
|
<PackageReference Include="CsvHelper" Version="28.0.1" />
|
||||||
<PackageReference Include="Discord.Net" Version="3.104.0" />
|
<PackageReference Include="Discord.Net" Version="3.204.0" />
|
||||||
<PackageReference Include="CoreCLR-NCalc" Version="2.2.110" />
|
<PackageReference Include="CoreCLR-NCalc" Version="2.2.110" />
|
||||||
<PackageReference Include="Google.Apis.Urlshortener.v1" Version="1.41.1.138" />
|
<PackageReference Include="Google.Apis.Urlshortener.v1" Version="1.41.1.138" />
|
||||||
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.57.0.2749" />
|
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.62.1.3205" />
|
||||||
<PackageReference Include="Google.Apis.Customsearch.v1" Version="1.49.0.2084" />
|
<PackageReference Include="Google.Apis.Customsearch.v1" Version="1.49.0.2084" />
|
||||||
<PackageReference Include="Google.Protobuf" Version="3.21.2" />
|
<PackageReference Include="Google.Protobuf" Version="3.21.2" />
|
||||||
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.47.0" />
|
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.47.0" />
|
||||||
@@ -52,12 +52,13 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" />
|
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="NonBlocking" Version="2.1.0" />
|
<PackageReference Include="NonBlocking" Version="2.1.0" />
|
||||||
<PackageReference Include="OneOf" Version="3.0.223" />
|
<PackageReference Include="OneOf" Version="3.0.223" />
|
||||||
<PackageReference Include="Scrutor" Version="4.2.0" />
|
<PackageReference Include="Scrutor" Version="4.2.0" />
|
||||||
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
|
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
|
||||||
<PackageReference Include="Serilog.Sinks.Seq" Version="5.1.1" />
|
<PackageReference Include="Serilog.Sinks.Seq" Version="5.1.1" />
|
||||||
|
<PackageReference Include="SharpToken" Version="1.2.14" />
|
||||||
<PackageReference Include="SixLabors.Fonts" Version="1.0.0-beta17" />
|
<PackageReference Include="SixLabors.Fonts" Version="1.0.0-beta17" />
|
||||||
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.3" />
|
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.3" />
|
||||||
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta14" />
|
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta14" />
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
using NadekoBot.Services.Currency;
|
using NadekoBot.Services.Currency;
|
||||||
|
|
||||||
namespace NadekoBot.Services;
|
namespace NadekoBot.Services;
|
||||||
|
|
||||||
@@ -27,13 +27,19 @@ public static class CurrencyServiceExtensions
|
|||||||
|
|
||||||
if (await fromWallet.Transfer(amount, toWallet, extra))
|
if (await fromWallet.Transfer(amount, toWallet, extra))
|
||||||
{
|
{
|
||||||
await to.SendConfirmAsync(ebs,
|
try
|
||||||
string.IsNullOrWhiteSpace(note)
|
{
|
||||||
? $"Received {formattedAmount} from {from} "
|
await to.SendConfirmAsync(ebs,
|
||||||
: $"Received {formattedAmount} from {from}: {note}");
|
string.IsNullOrWhiteSpace(note)
|
||||||
|
? $"Received {formattedAmount} from {from} "
|
||||||
|
: $"Received {formattedAmount} from {from}: {note}");
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
//ignored
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -104,8 +104,7 @@ public sealed class GamblingTxTracker : ITxTracker, INService, IReadyExecutor
|
|||||||
public async Task<IReadOnlyCollection<GamblingStats>> GetAllAsync()
|
public async Task<IReadOnlyCollection<GamblingStats>> GetAllAsync()
|
||||||
{
|
{
|
||||||
await using var ctx = _db.GetDbContext();
|
await using var ctx = _db.GetDbContext();
|
||||||
return await ctx
|
return await ctx.Set<GamblingStats>()
|
||||||
.GetTable<GamblingStats>()
|
.ToListAsyncEF();
|
||||||
.ToListAsync();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -184,8 +184,11 @@ public sealed class BotCredsProvider : IBotCredsProvider
|
|||||||
var creds = Yaml.Deserializer.Deserialize<Creds>(File.ReadAllText(CREDS_FILE_NAME));
|
var creds = Yaml.Deserializer.Deserialize<Creds>(File.ReadAllText(CREDS_FILE_NAME));
|
||||||
if (creds.Version <= 5)
|
if (creds.Version <= 5)
|
||||||
{
|
{
|
||||||
creds.Version = 6;
|
|
||||||
creds.BotCache = BotCacheImplemenation.Redis;
|
creds.BotCache = BotCacheImplemenation.Redis;
|
||||||
|
}
|
||||||
|
if (creds.Version <= 6)
|
||||||
|
{
|
||||||
|
creds.Version = 7;
|
||||||
File.WriteAllText(CREDS_FILE_NAME, Yaml.Serializer.Serialize(creds));
|
File.WriteAllText(CREDS_FILE_NAME, Yaml.Serializer.Serialize(creds));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -57,7 +57,7 @@ public sealed partial class GoogleApiService : IGoogleApiService, INService
|
|||||||
return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId);
|
return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<string>> GetRelatedVideosAsync(string id, int count = 1, string user = null)
|
public async Task<IEnumerable<string>> GetRelatedVideosAsync(string id, int count = 2, string user = null)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(id))
|
if (string.IsNullOrWhiteSpace(id))
|
||||||
throw new ArgumentNullException(nameof(id));
|
throw new ArgumentNullException(nameof(id));
|
||||||
@@ -67,10 +67,14 @@ public sealed partial class GoogleApiService : IGoogleApiService, INService
|
|||||||
|
|
||||||
var query = _yt.Search.List("snippet");
|
var query = _yt.Search.List("snippet");
|
||||||
query.MaxResults = count;
|
query.MaxResults = count;
|
||||||
query.RelatedToVideoId = id;
|
query.Q = id;
|
||||||
|
// query.RelatedToVideoId = id;
|
||||||
query.Type = "video";
|
query.Type = "video";
|
||||||
query.QuotaUser = user;
|
query.QuotaUser = user;
|
||||||
return (await query.ExecuteAsync()).Items.Select(i => "https://www.youtube.com/watch?v=" + i.Id.VideoId);
|
// bad workaround as there's no replacement for related video querying right now.
|
||||||
|
// Query youtube with the id of the video, take a second video in the results
|
||||||
|
// skip the first one as that's probably the same video.
|
||||||
|
return (await query.ExecuteAsync()).Items.Select(i => "https://www.youtube.com/watch?v=" + i.Id.VideoId).Skip(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<string>> GetVideoLinksByKeywordAsync(string keywords, int count = 1)
|
public async Task<IEnumerable<string>> GetVideoLinksByKeywordAsync(string keywords, int count = 1)
|
||||||
|
@@ -7,7 +7,7 @@ namespace NadekoBot.Services;
|
|||||||
|
|
||||||
public sealed class StatsService : IStatsService, IReadyExecutor, INService
|
public sealed class StatsService : IStatsService, IReadyExecutor, INService
|
||||||
{
|
{
|
||||||
public const string BOT_VERSION = "4.3.11";
|
public const string BOT_VERSION = "4.3.22";
|
||||||
|
|
||||||
public string Author
|
public string Author
|
||||||
=> "Kwoth#2452";
|
=> "Kwoth#2452";
|
||||||
|
@@ -167,8 +167,8 @@ public static class MessageChannelExtensions
|
|||||||
private const string BUTTON_LEFT = "BUTTON_LEFT";
|
private const string BUTTON_LEFT = "BUTTON_LEFT";
|
||||||
private const string BUTTON_RIGHT = "BUTTON_RIGHT";
|
private const string BUTTON_RIGHT = "BUTTON_RIGHT";
|
||||||
|
|
||||||
private static readonly IEmote _arrowLeft = Emote.Parse("<:x:969658061805465651>");
|
private static readonly IEmote _arrowLeft = Emote.Parse("<:x:1232256519844790302>");
|
||||||
private static readonly IEmote _arrowRight = Emote.Parse("<:x:969658062220701746>");
|
private static readonly IEmote _arrowRight = Emote.Parse("<:x:1232256515298295838>");
|
||||||
|
|
||||||
public static Task SendPaginatedConfirmAsync(
|
public static Task SendPaginatedConfirmAsync(
|
||||||
this ICommandContext ctx,
|
this ICommandContext ctx,
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
# DO NOT CHANGE
|
# DO NOT CHANGE
|
||||||
version: 6
|
version: 7
|
||||||
# Bot token. Do not share with anyone ever -> https://discordapp.com/developers/applications/
|
# Bot token. Do not share with anyone ever -> https://discordapp.com/developers/applications/
|
||||||
token: ''
|
token: ''
|
||||||
# List of Ids of the users who have bot owner permissions
|
# List of Ids of the users who have bot owner permissions
|
||||||
@@ -56,6 +56,8 @@ patreon:
|
|||||||
botListToken: ''
|
botListToken: ''
|
||||||
# Official cleverbot api key.
|
# Official cleverbot api key.
|
||||||
cleverbotApiKey: ''
|
cleverbotApiKey: ''
|
||||||
|
# Official GPT-3 api key.
|
||||||
|
gpt3ApiKey: ''
|
||||||
# Which cache implementation should bot use.
|
# Which cache implementation should bot use.
|
||||||
# 'memory' - Cache will be in memory of the bot's process itself. Only use this on bots with a single shard. When the bot is restarted the cache is reset.
|
# 'memory' - Cache will be in memory of the bot's process itself. Only use this on bots with a single shard. When the bot is restarted the cache is reset.
|
||||||
# 'redis' - Uses redis (which needs to be separately downloaded and installed). The cache will persist through bot restarts. You can configure connection string in creds.yml
|
# 'redis' - Uses redis (which needs to be separately downloaded and installed). The cache will persist through bot restarts. You can configure connection string in creds.yml
|
||||||
|
@@ -195,6 +195,8 @@ setnick:
|
|||||||
setavatar:
|
setavatar:
|
||||||
- setavatar
|
- setavatar
|
||||||
- setav
|
- setav
|
||||||
|
setbanner:
|
||||||
|
- setbanner
|
||||||
setgame:
|
setgame:
|
||||||
- setgame
|
- setgame
|
||||||
send:
|
send:
|
||||||
@@ -647,10 +649,6 @@ chucknorris:
|
|||||||
magicitem:
|
magicitem:
|
||||||
- magicitem
|
- magicitem
|
||||||
- mi
|
- mi
|
||||||
revav:
|
|
||||||
- revav
|
|
||||||
revimg:
|
|
||||||
- revimg
|
|
||||||
safebooru:
|
safebooru:
|
||||||
- safebooru
|
- safebooru
|
||||||
wiki:
|
wiki:
|
||||||
@@ -664,8 +662,6 @@ avatar:
|
|||||||
- av
|
- av
|
||||||
hentai:
|
hentai:
|
||||||
- hentai
|
- hentai
|
||||||
nhentai:
|
|
||||||
- nhentai
|
|
||||||
danbooru:
|
danbooru:
|
||||||
- danbooru
|
- danbooru
|
||||||
derpibooru:
|
derpibooru:
|
||||||
@@ -807,6 +803,7 @@ hentaibomb:
|
|||||||
- hentaibomb
|
- hentaibomb
|
||||||
cleverbot:
|
cleverbot:
|
||||||
- cleverbot
|
- cleverbot
|
||||||
|
- chatgpt
|
||||||
shorten:
|
shorten:
|
||||||
- shorten
|
- shorten
|
||||||
wikia:
|
wikia:
|
||||||
@@ -1117,6 +1114,8 @@ clubapply:
|
|||||||
- clubapply
|
- clubapply
|
||||||
clubaccept:
|
clubaccept:
|
||||||
- clubaccept
|
- clubaccept
|
||||||
|
clubreject:
|
||||||
|
- clubreject
|
||||||
clubleave:
|
clubleave:
|
||||||
- clubleave
|
- clubleave
|
||||||
clubdisband:
|
clubdisband:
|
||||||
@@ -1390,3 +1389,5 @@ autopublish:
|
|||||||
doas:
|
doas:
|
||||||
- doas
|
- doas
|
||||||
- execas
|
- execas
|
||||||
|
cacheusers:
|
||||||
|
- cacheusers
|
@@ -1,5 +1,5 @@
|
|||||||
# DO NOT CHANGE
|
# DO NOT CHANGE
|
||||||
version: 1
|
version: 3
|
||||||
# Hangman related settings (.hangman command)
|
# Hangman related settings (.hangman command)
|
||||||
hangman:
|
hangman:
|
||||||
# The amount of currency awarded to the winner of a hangman game
|
# The amount of currency awarded to the winner of a hangman game
|
||||||
@@ -9,7 +9,7 @@ trivia:
|
|||||||
# The amount of currency awarded to the winner of the trivia game.
|
# The amount of currency awarded to the winner of the trivia game.
|
||||||
currencyReward: 0
|
currencyReward: 0
|
||||||
# Users won't be able to start trivia games which have
|
# Users won't be able to start trivia games which have
|
||||||
# a smaller win requirement than the one specified by this setting.
|
# a smaller win requirement than the one specified by this setting.
|
||||||
minimumWinReq: 1
|
minimumWinReq: 1
|
||||||
# List of responses for the .8ball command. A random one will be selected every time
|
# List of responses for the .8ball command. A random one will be selected every time
|
||||||
eightBallResponses:
|
eightBallResponses:
|
||||||
@@ -54,3 +54,22 @@ raceAnimals:
|
|||||||
name: Crab
|
name: Crab
|
||||||
- icon: "🦄"
|
- icon: "🦄"
|
||||||
name: Unicorn
|
name: Unicorn
|
||||||
|
# Which chatbot API should bot use.
|
||||||
|
# 'cleverbot' - bot will use Cleverbot API.
|
||||||
|
# 'gpt3' - bot will use GPT-3 API
|
||||||
|
chatBot: Gpt3
|
||||||
|
|
||||||
|
chatGpt:
|
||||||
|
# Which GPT-3 Model should bot use.
|
||||||
|
# gpt35turbo - cheapest
|
||||||
|
# gpt4 - 30x more expensive, higher quality
|
||||||
|
# gp432k - same model as above, but with a 32k token limit
|
||||||
|
modelName: Gpt35Turbo
|
||||||
|
# How should the chat bot behave, whats its personality? (Usage of this counts towards the max tokens)
|
||||||
|
personalityPrompt: You are a chat bot willing to have a conversation with anyone about anything.
|
||||||
|
# The maximum number of messages in a conversation that can be remembered. (This will increase the number of tokens used)
|
||||||
|
chatHistory: 5
|
||||||
|
# The maximum number of tokens to use per GPT-3 API call
|
||||||
|
maxTokens: 100
|
||||||
|
# The minimum number of tokens to use per GPT-3 API call, such that chat history is removed to make room.
|
||||||
|
minTokens: 30
|
@@ -1,5 +1,5 @@
|
|||||||
# DO NOT CHANGE
|
# DO NOT CHANGE
|
||||||
version: 1
|
version: 2
|
||||||
# Which engine should .search command
|
# Which engine should .search command
|
||||||
# 'google_scrape' - default. Scrapes the webpage for results. May break. Requires no api keys.
|
# 'google_scrape' - default. Scrapes the webpage for results. May break. Requires no api keys.
|
||||||
# 'google' - official google api. Requires googleApiKey and google.searchId set in creds.yml
|
# 'google' - official google api. Requires googleApiKey and google.searchId set in creds.yml
|
||||||
@@ -18,7 +18,7 @@ imgSearchEngine: Google
|
|||||||
# - `ytdlp` - recommended easy, uses `yt-dlp`. Requires `yt-dlp` to be installed and it's path added to env variables
|
# - `ytdlp` - recommended easy, uses `yt-dlp`. Requires `yt-dlp` to be installed and it's path added to env variables
|
||||||
#
|
#
|
||||||
# - `invidious` - recommended advanced, uses invidious api. Requires at least one invidious instance specified in the `invidiousInstances` property
|
# - `invidious` - recommended advanced, uses invidious api. Requires at least one invidious instance specified in the `invidiousInstances` property
|
||||||
ytProvider: Ytdl
|
ytProvider: Ytdlp
|
||||||
# Set the searx instance urls in case you want to use 'searx' for either img or web search.
|
# Set the searx instance urls in case you want to use 'searx' for either img or web search.
|
||||||
# Nadeko will use a random one for each request.
|
# Nadeko will use a random one for each request.
|
||||||
# Use a fully qualified url. Example: `https://my-searx-instance.mydomain.com`
|
# Use a fully qualified url. Example: `https://my-searx-instance.mydomain.com`
|
||||||
@@ -41,3 +41,7 @@ searxInstances: []
|
|||||||
# Instances specified must have api available.
|
# Instances specified must have api available.
|
||||||
# You check that by opening an api endpoint in your browser. For example: https://my-invidious-instance.mydomain.com/api/v1/trending
|
# You check that by opening an api endpoint in your browser. For example: https://my-invidious-instance.mydomain.com/api/v1/trending
|
||||||
invidiousInstances: []
|
invidiousInstances: []
|
||||||
|
# Maximum number of followed streams per server
|
||||||
|
followedStreams:
|
||||||
|
# Maximum number of streams that each server can follow. -1 for infinite
|
||||||
|
maxCount: 10
|
||||||
|
@@ -402,6 +402,10 @@ setavatar:
|
|||||||
desc: "Sets a new avatar image for the NadekoBot. Parameter is a direct link to an image."
|
desc: "Sets a new avatar image for the NadekoBot. Parameter is a direct link to an image."
|
||||||
args:
|
args:
|
||||||
- "https://i.imgur.com/xTG3a1I.jpg"
|
- "https://i.imgur.com/xTG3a1I.jpg"
|
||||||
|
setbanner:
|
||||||
|
desc: "Sets a new banner image for the NadekoBot. Parameter is a direct link to an image. Supports gifs."
|
||||||
|
args:
|
||||||
|
- "https://i.imgur.com/xTG3a1I.jpg"
|
||||||
setgame:
|
setgame:
|
||||||
desc: "Sets the bots game status to either Playing, Listening, or Watching."
|
desc: "Sets the bots game status to either Playing, Listening, or Watching."
|
||||||
args:
|
args:
|
||||||
@@ -1117,11 +1121,6 @@ hentai:
|
|||||||
desc: "Shows a hentai image from a random website (gelbooru, danbooru, konachan or yandere) with a given tag. Tag(s) are optional but preferred. Maximum is usually 2 tags. Only 1 tag allowed."
|
desc: "Shows a hentai image from a random website (gelbooru, danbooru, konachan or yandere) with a given tag. Tag(s) are optional but preferred. Maximum is usually 2 tags. Only 1 tag allowed."
|
||||||
args:
|
args:
|
||||||
- "yuri"
|
- "yuri"
|
||||||
nhentai:
|
|
||||||
desc: "Shows basic information about a hentai with the specified id, or a valid nhentai search query."
|
|
||||||
args:
|
|
||||||
- "273426"
|
|
||||||
- "cute girl"
|
|
||||||
autohentai:
|
autohentai:
|
||||||
desc: "Posts a hentai every X seconds with a random tag from the provided tags. Use `|` to separate tag groups. Random group will be chosen every time the image is sent. Max 2 tags per group. 20 seconds minimum. Provide no parameters to disable."
|
desc: "Posts a hentai every X seconds with a random tag from the provided tags. Use `|` to separate tag groups. Random group will be chosen every time the image is sent. Max 2 tags per group. 20 seconds minimum. Provide no parameters to disable."
|
||||||
args:
|
args:
|
||||||
@@ -1377,7 +1376,7 @@ listservers:
|
|||||||
args:
|
args:
|
||||||
- "3"
|
- "3"
|
||||||
cleverbot:
|
cleverbot:
|
||||||
desc: "Toggles cleverbot session. When enabled, the bot will reply to messages starting with bot mention in the server. Expressions starting with %bot.mention% won't work if cleverbot is enabled."
|
desc: "Toggles cleverbot/chatgpt session. When enabled, the bot will reply to messages starting with bot mention in the server. Expressions starting with %bot.mention% won't work if cleverbot/chatgpt is enabled."
|
||||||
args:
|
args:
|
||||||
- ""
|
- ""
|
||||||
shorten:
|
shorten:
|
||||||
@@ -1564,7 +1563,7 @@ timezones:
|
|||||||
args:
|
args:
|
||||||
- ""
|
- ""
|
||||||
timezone:
|
timezone:
|
||||||
desc: "Sets this guilds timezone. This affects bot's time output in this server (logs, etc..)"
|
desc: "Sets this guilds timezone. This affects bot's time output in this server (logs, etc..) **Setting timezone requires Administrator server permission.**"
|
||||||
args:
|
args:
|
||||||
- ""
|
- ""
|
||||||
- "GMT Standard Time"
|
- "GMT Standard Time"
|
||||||
@@ -1934,6 +1933,10 @@ clubaccept:
|
|||||||
desc: "Accept a user who applied to your club."
|
desc: "Accept a user who applied to your club."
|
||||||
args:
|
args:
|
||||||
- "user#1337"
|
- "user#1337"
|
||||||
|
clubreject:
|
||||||
|
desc: "Reject a user who applied to your club."
|
||||||
|
args:
|
||||||
|
- "user#1337"
|
||||||
clubleave:
|
clubleave:
|
||||||
desc: "Leaves the club you're currently in."
|
desc: "Leaves the club you're currently in."
|
||||||
args:
|
args:
|
||||||
@@ -2364,3 +2367,8 @@ doas:
|
|||||||
desc: "Execute the command as if you were the target user. Requires bot ownership and server administrator permission."
|
desc: "Execute the command as if you were the target user. Requires bot ownership and server administrator permission."
|
||||||
args:
|
args:
|
||||||
- "@Thief .give all @Admin"
|
- "@Thief .give all @Admin"
|
||||||
|
cacheusers:
|
||||||
|
desc: Caches users of a Discord server and saves them to the database.
|
||||||
|
args:
|
||||||
|
- ""
|
||||||
|
- "serverId"
|
@@ -184,6 +184,7 @@
|
|||||||
"setrole": "Successfully added role {0} to user {1}",
|
"setrole": "Successfully added role {0} to user {1}",
|
||||||
"setrole_err": "Failed to add role. I have insufficient permissions.",
|
"setrole_err": "Failed to add role. I have insufficient permissions.",
|
||||||
"set_avatar": "New avatar set!",
|
"set_avatar": "New avatar set!",
|
||||||
|
"set_banner": "New banner set!",
|
||||||
"set_channel_name": "New channel name set.",
|
"set_channel_name": "New channel name set.",
|
||||||
"set_game": "New game set!",
|
"set_game": "New game set!",
|
||||||
"set_stream": "New stream set!",
|
"set_stream": "New stream set!",
|
||||||
@@ -838,7 +839,7 @@
|
|||||||
"server_leaderboard": "Server XP Leaderboard",
|
"server_leaderboard": "Server XP Leaderboard",
|
||||||
"global_leaderboard": "Global XP Leaderboard",
|
"global_leaderboard": "Global XP Leaderboard",
|
||||||
"modified": "Modified server XP of the user {0} by {1}",
|
"modified": "Modified server XP of the user {0} by {1}",
|
||||||
"club_insuff_lvl": "You're insufficient level to join that club.",
|
"club_already_applied": "You've already applied to that club.",
|
||||||
"club_join_banned": "You're banned from that club.",
|
"club_join_banned": "You're banned from that club.",
|
||||||
"club_already_in": "You are already a member of a club.",
|
"club_already_in": "You are already a member of a club.",
|
||||||
"club_create_error_name": "Failed creating the club. A club with that name already exists.",
|
"club_create_error_name": "Failed creating the club. A club with that name already exists.",
|
||||||
@@ -848,6 +849,7 @@
|
|||||||
"club_not_exists": "That club doesn't exist.",
|
"club_not_exists": "That club doesn't exist.",
|
||||||
"club_applied": "You've applied for membership in {0} club.",
|
"club_applied": "You've applied for membership in {0} club.",
|
||||||
"club_accepted": "Accepted user {0} to the club.",
|
"club_accepted": "Accepted user {0} to the club.",
|
||||||
|
"club_rejected": "The application by {0} has been rejected.",
|
||||||
"club_accept_invalid_applicant": "That user has not applied to your club.",
|
"club_accept_invalid_applicant": "That user has not applied to your club.",
|
||||||
"club_left": "You've left the club.",
|
"club_left": "You've left the club.",
|
||||||
"club_not_in_a_club": "You are not in a club.",
|
"club_not_in_a_club": "You are not in a club.",
|
||||||
@@ -1057,5 +1059,7 @@
|
|||||||
"sticker_missing_name": "Please specify a name for the sticker.",
|
"sticker_missing_name": "Please specify a name for the sticker.",
|
||||||
"thread_deleted": "Thread Deleted",
|
"thread_deleted": "Thread Deleted",
|
||||||
"thread_created": "Thread Created",
|
"thread_created": "Thread Created",
|
||||||
"supported_languages": "Supported Languages"
|
"supported_languages": "Supported Languages",
|
||||||
|
"cache_users_pending": "Updating users, please wait...",
|
||||||
|
"cache_users_done": "{0} users were added and {1} users were updated."
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@
|
|||||||
<Version>1.0.2</Version>
|
<Version>1.0.2</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="Serilog" Version="2.11.0" />
|
<PackageReference Include="Serilog" Version="2.11.0" />
|
||||||
<PackageReference Include="System.Threading.Channels" Version="6.0.0" />
|
<PackageReference Include="System.Threading.Channels" Version="6.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
@@ -237,20 +237,25 @@ namespace Ayu.Discord.Voice
|
|||||||
_udpEp = new(IPAddress.Parse(ready.Ip), ready.Port);
|
_udpEp = new(IPAddress.Parse(ready.Ip), ready.Port);
|
||||||
|
|
||||||
var ssrcBytes = BitConverter.GetBytes(Ssrc);
|
var ssrcBytes = BitConverter.GetBytes(Ssrc);
|
||||||
var ipDiscoveryData = new byte[70];
|
Array.Reverse(ssrcBytes);
|
||||||
Buffer.BlockCopy(ssrcBytes, 0, ipDiscoveryData, 0, ssrcBytes.Length);
|
var ipDiscoveryData = new byte[74];
|
||||||
|
Buffer.BlockCopy(ssrcBytes, 0, ipDiscoveryData, 4, ssrcBytes.Length);
|
||||||
|
ipDiscoveryData[0] = 0x00;
|
||||||
|
ipDiscoveryData[1] = 0x01;
|
||||||
|
ipDiscoveryData[2] = 0x00;
|
||||||
|
ipDiscoveryData[3] = 0x46;
|
||||||
await _udpClient.SendAsync(ipDiscoveryData, ipDiscoveryData.Length, _udpEp);
|
await _udpClient.SendAsync(ipDiscoveryData, ipDiscoveryData.Length, _udpEp);
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
var buffer = _udpClient.Receive(ref _udpEp);
|
var buffer = _udpClient.Receive(ref _udpEp);
|
||||||
|
|
||||||
if (buffer.Length == 70)
|
if (buffer.Length == 74)
|
||||||
{
|
{
|
||||||
//Log.Information("Received IP discovery data.");
|
//Log.Information("Received IP discovery data.");
|
||||||
|
|
||||||
var myIp = Encoding.UTF8.GetString(buffer, 4, buffer.Length - 8);
|
var myIp = Encoding.UTF8.GetString(buffer, 8, buffer.Length - 10);
|
||||||
MyIp = myIp.TrimEnd('\0');
|
MyIp = myIp.TrimEnd('\0');
|
||||||
MyPort = BitConverter.ToUInt16(buffer, buffer.Length - 2);
|
MyPort = (ushort)((buffer[^2] << 8) | buffer[^1]);
|
||||||
|
|
||||||
//Log.Information("{MyIp}:{MyPort}", MyIp, MyPort);
|
//Log.Information("{MyIp}:{MyPort}", MyIp, MyPort);
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user