Compare commits

...

19 Commits
3.0.1 ... 3.0.2

Author SHA1 Message Date
Kwoth
d115261536 Fixed .log commands 2021-09-12 22:07:56 +02:00
Kwoth
0429210a73 .boost should now us the correct channel, and it should send a message for users boosting the same server more than once 2021-09-12 21:05:19 +02:00
Kwoth
8ee1160a00 Added .boost, .boostmsg and .boostdel commands which allow you to have customizable messages when someone boosts your server, with auto-deletion support
- Updated response embed colors in greet commands
- Updated .greetmsg and .byemsg command help to match the new .boost command help
2021-09-12 20:44:35 +02:00
Kwoth
a27ea7a0aa Merge branch 'v3' of https://gitlab.com/kwoth/nadekobot into v3 2021-09-12 20:01:16 +02:00
Kwoth
9396f59a34 Update responses.de-DE.json (POEditor.com) 2021-09-12 17:58:57 +00:00
Kwoth
37cdea4f6a Removed .novel command as it no longer works 2021-09-12 13:31:57 +02:00
Kwoth
d028e23bc1 .timely will now correctly use Ok color 2021-09-12 01:22:13 +02:00
Kwoth
1df947d54b .rero now optionally takes a message id to which to attach the reaction roles 2021-09-12 01:07:19 +02:00
Kwoth
596a5c05e0 docs: Fixed more indentation in osx and migration guides 2021-09-12 00:18:54 +02:00
Kwoth
1d5a702b46 docs: Updated bot sharding guide in advanced creds guide, Added comments to coord.yml, Updated manual migration guide with correct indentation 2021-09-12 00:09:55 +02:00
Kwoth
712cb9300f docs: Fixed up jsons-explained.md (thx ala) 2021-09-11 22:48:48 +02:00
Kwoth
ab0d013035 docs: removed from source sidebar link 2021-09-11 22:28:28 +02:00
Kwoth
46b384f0f4 Docs format and link fixes 2021-09-11 16:52:14 +02:00
Kwoth
1284312a55 Clarified that running the 2.x bot prior to migration is mandatory 2021-09-11 00:58:22 +02:00
Kwoth
42bdc6417c Updated osx guide with instructions on installing wget 2021-09-11 00:47:08 +02:00
Kwoth
3715dd4e00 Fixed version in the changelog 2021-09-11 00:16:14 +02:00
Kwoth
ef13020d96 Updated changelog 2021-09-11 00:14:55 +02:00
Kwoth
dd708d4b7c Slight change to windows updater migration guide 2021-09-11 00:03:52 +02:00
Kwoth
8735dcf94d Upped version to 3.0.1 2021-09-11 00:01:05 +02:00
34 changed files with 9588 additions and 1190 deletions

View File

@@ -4,7 +4,32 @@ Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.
## Unreleased ## Unreleased
### Added
- `.rero` now optionally takes a message id to which to attach the reaction roles
- Fully translated to German 🎉
- Added `.boost`, `.boostmsg` and `.boostdel` commands which allow you to have customizable messages when someone boosts your server, with auto-deletion support
### Changed
- Updated `.greetmsg` and `.byemsg` command help to match the new `.boost` command help
- Updated response embed colors in greet commands
- Success -> green
- Warning or Disable -> yellow.
### Fixed
- `.timely` will now correctly use `Ok` color
### Removed
- Removed `.novel` command as it no longer works
## [3.0.1] - 10.09.2021
### Fixed
- Fixed some issues with the embeds not showing the correct data
## [3.0.0] - 06.09.2021 ## [3.0.0] - 06.09.2021

View File

@@ -4,6 +4,7 @@
1. Run your NadekoBot Updater first, and **make sure your bot is updated to at least 2.46.5** 1. Run your NadekoBot Updater first, and **make sure your bot is updated to at least 2.46.5**
- **Run your 2.46.5 Bot** and make sure it works, and then **stop it** - **Run your 2.46.5 Bot** and make sure it works, and then **stop it**
- Close your old NadekoBot Updater
2. Get the new NadekoBot v3 Updater [here](https://dl.nadeko.bot/v3) 2. Get the new NadekoBot v3 Updater [here](https://dl.nadeko.bot/v3)
3. Click on the + icon to add a new bot 3. Click on the + icon to add a new bot
4. Next to the path, click on the folder icon and select the folder where your 2.46.5 bot is 4. Next to the path, click on the folder icon and select the folder where your 2.46.5 bot is
@@ -17,7 +18,7 @@
1. In order to migrate a bot hosted on **Linux**, first update your current version to the latest 2.x version using the 2.x installer, run the bot, and make sure it works. Then: 1. In order to migrate a bot hosted on **Linux**, first update your current version to the latest 2.x version using the 2.x installer, run the bot, and make sure it works. Then:
- Run the **old** installer with `cd ~ && wget -N https://github.com/Kwoth/NadekoBot-BashScript/raw/1.9/linuxAIO.sh && bash linuxAIO.sh` - Run the **old** installer with `cd ~ && wget -N https://github.com/Kwoth/NadekoBot-BashScript/raw/1.9/linuxAIO.sh && bash linuxAIO.sh`
- Run option **1** again - Run option **1** again
- Run the bot - You **MUST** Run the bot now to ensure database is ready for migration
- Type `.stats` and ensure the version is `2.46.5` or later - Type `.stats` and ensure the version is `2.46.5` or later
- Stop the bot - Stop the bot
2. Make sure your bot's folder is called `NadekoBot` 2. Make sure your bot's folder is called `NadekoBot`
@@ -33,14 +34,17 @@
- `.stats` to ensure owner id (credentials) is correct - `.stats` to ensure owner id (credentials) is correct
- `.lcr` to see custom reactions - `.lcr` to see custom reactions
- `.lp` to list permissions - `.lp` to list permissions
5. 🎉 Enjoy. If you want to learn how to update the bot, click (here)[../linux-guide/#update-instructions]. 5. 🎉 Enjoy. If you want to learn how to update the bot, click [here](../linux-guide/#update-instructions)
## Manual ## Manual
⚠ NOT RECOMMENDED ⚠ NOT RECOMMENDED
⚠ NadekoBot v3 requires [.net 5](https://dotnet.microsoft.com/download/dotnet/5.0) ⚠ NadekoBot v3 requires [.net 5](https://dotnet.microsoft.com/download/dotnet/5.0)
1. In order to migrate a bot hosted **on Linux or from source on Windows**, first update your current version to the latest 2.x version using the 2.x installer, run the bot, and make sure it works. Then: 1. In order to migrate a bot hosted **on Linux or from source on Windows**
- First update your current version to the latest 2.x version using the 2.x installer
- Then you **must** run the bot to prepare the database for the migration, and make sure the bot works prior to upgrade.
Then:
2. Rename your old nadeko bot folder to `nadekobot_2x` 2. Rename your old nadeko bot folder to `nadekobot_2x`
- `mv NadekoBot nadekobot_2x` - `mv NadekoBot nadekobot_2x`
3. Build the new version and move old data to the output folder 3. Build the new version and move old data to the output folder

View File

@@ -1,6 +1,14 @@
### Linux From Source ## MacOS From Source
Open Terminal (if you're on an installation with a window manager) and navigate to the location where you want to install the bot (for example `cd ~`) Open Terminal (if you don't know how to, click on the magnifying glass on the top right corner of your screen and type **Terminal** on the window that pops up) and navigate to the location where you want to install the bot (for example `cd ~`)
##### Installing Homebrew and wget
*Skip this step if you already have homebrew installed*
- Copy and paste this command, then press Enter:
- `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
- Install wget
- `brew install wget`
##### Installation Instructions ##### Installation Instructions
@@ -8,7 +16,8 @@ Open Terminal (if you're on an installation with a window manager) and navigate
2. Install prerequisites (type `1` and press enter) 2. Install prerequisites (type `1` and press enter)
3. Download the bot (type `2` and press enter) 3. Download the bot (type `2` and press enter)
4. Exit the installer in order to set up your `creds.yml` 4. Exit the installer in order to set up your `creds.yml`
5. Copy the creds.yml template `cp nadekobot/output/creds_example.yml nadekobot/output/creds.yml` 5. Copy the creds.yml template
`cp nadekobot/output/creds_example.yml nadekobot/output/creds.yml`
6. Open `nadekobot/output/creds.yml` with your favorite text editor. We will use nano here 6. Open `nadekobot/output/creds.yml` with your favorite text editor. We will use nano here
- `nano nadekobot/output/creds.yml` - `nano nadekobot/output/creds.yml`
7. [Enter your bot's token](#creds-guide) 7. [Enter your bot's token](#creds-guide)
@@ -26,7 +35,7 @@ Open Terminal (if you're on an installation with a window manager) and navigate
4. Run the bot (type `3` and press enter) 4. Run the bot (type `3` and press enter)
5. 🎉 5. 🎉
### Linux Release ## MacOS Manual Release installation instructions
##### Installation Instructions ##### Installation Instructions

View File

@@ -18,7 +18,7 @@ This part is completely optional, **however it's necessary for music and a few o
- Open up `creds.yml` and look for `GoogleAPIKey`, paste your API key after the `:`. - Open up `creds.yml` and look for `GoogleAPIKey`, paste your API key after the `:`.
- It should look like this: - It should look like this:
```yml ```yml
GoogleApiKey: "AIzaSyDSci1sdlWQOWNVj1vlXxxxxxbk0oWMEzM", GoogleApiKey: "AIzaSyDSci1sdlWQOWNVj1vlXxxxxxbk0oWMEzM"
``` ```
- **MashapeKey** - **MashapeKey**
- Required for Hearthstone cards. - Required for Hearthstone cards.
@@ -42,9 +42,8 @@ This part is completely optional, **however it's necessary for music and a few o
- Select `Chat Bot` from the Category dropdown - Select `Chat Bot` from the Category dropdown
- Once created, clicking on your application will show a new Client ID field - Once created, clicking on your application will show a new Client ID field
- Copy it to your creds.yml as shown below - Copy it to your creds.yml as shown below
- *(if you're adding it as the last key inside your creds.yml, remove the trailling comma from the example below)*
```yml ```yml
TwitchClientId: "516tr61tr1qweqwe86trg3g", TwitchClientId: "516tr61tr1qweqwe86trg3g"
``` ```
- **LocationIqApiKey** - **LocationIqApiKey**
- Optional. Used only for the `.time` command. https://locationiq.com api key (register and you will receive the token in the email). - Optional. Used only for the `.time` command. https://locationiq.com api key (register and you will receive the token in the email).
@@ -75,43 +74,93 @@ RestartCommand:
For Windows (Source), Linux or OSX, add this to your `creds.yml` For Windows (Source), Linux or OSX, add this to your `creds.yml`
```yml ```yml
"RestartCommand": { RestartCommand:
"Cmd": "dotnet", Cmd: dotnet
"Args": "run -c Release" Args: "NadekoBot.dll -- {0}"
},
``` ```
--- ---
#### End Result #### End Result
**This is an example of how the `creds.yml` looks like with multiple owners, the restart command (optional) and all the API keys (also optional):** **This is an example of how the `creds.yml` looks like with multiple owners, the restart command (optional) and some of the API keys (also optional):**
```yml ```yml
{ # DO NOT CHANGE
"Token": "MTc5MzcyXXX2MDI1ODY3MjY0.ChKs4g.I8J_R9XX0t-QY-0PzXXXiN0-7vo", version: 1
"OwnerIds": [ # Bot token. Do not share with anyone ever -> https://discordapp.com/developers/applications/
token: 'MTE5Nzc3MDIxMzE5NTc3NjEw.VlhNCw.BuqJFyzdIUAK1PRf1eK1Cu89Jew'
# List of Ids of the users who have bot owner permissions
# **DO NOT ADD PEOPLE YOU DON'T TRUST**
ownerIds: [
105635123466156544, 105635123466156544,
145521851676884992, 145521851676884992,
341420590009417729 341420590009417729
], ]
"GoogleApiKey": "AIzaSyDSci1sdlWQOWNVj1vlXxxxxxbk0oWMEzM", # The number of shards that the bot will running on.
"MashapeKey": "4UrKpcWXc2mshS8RKi00000y8Kf5p1Q8kI6jsn32bmd8oVWiY7", # Leave at 1 if you don't know what you're doing.
"OsuApiKey": "4c8c8fdff8e1234581725db27fd140a7d93320d6", totalShards: 1
"CleverbotApiKey": "", # Login to https://console.cloud.google.com, create a new project, go to APIs & Services -> Library -> YouTube Data API and enable it.
"Db": null, # Then, go to APIs and Services -> Credentials and click Create credentials -> API key.
"TotalShards": 1, # Used only for Youtube Data Api (at the moment).
"PatreonAccessToken": "", googleApiKey: 'AIzaSyDScfdfdfi1sdlWQOWxxxxxbk0oWMEzM'
"PatreonCampaignId": "334038", # Settings for voting system for discordbots. Meant for use on global Nadeko.
"RestartCommand": { votes:
"Cmd": "NadekoBot.exe" url: ''
}, key: ''
"ShardRunCommand": "", # Patreon auto reward system settings.
"ShardRunArguments": "", # go to https://www.patreon.com/portal -> my clients -> create client
"ShardRunPort": null, patreon:
"TwitchClientId": null, # Access token. You have to manually update this 1st of each month by refreshing the token on https://patreon.com/portal
"RedisOptions": null accessToken: ''
} # Unused atm
refreshToken: ''
# Unused atm
clientSecret: ''
# Campaign ID of your patreon page. Go to your patreon page (make sure you're logged in) and type "prompt('Campaign ID', window.patreon.bootstrap.creator.data.id);" in the console. (ctrl + shift + i)
campaignId: ''
# Api key for sending stats to DiscordBotList.
botListToken: ''
# Official cleverbot api key.
cleverbotApiKey: ''
# Redis connection string. Don't change if you don't know what you're doing.
redisOptions: localhost:6379,syncTimeout=30000,responseTimeout=30000,allowAdmin=true,password=
# Database options. Don't change if you don't know what you're doing. Leave null for default values
db:
# Database type. Only sqlite supported atm
type: sqlite
# Connection string. Will default to "Data Source=data/NadekoBot.db"
connectionString: Data Source=data/NadekoBot.db
# Address and port of the coordinator endpoint. Leave empty for default.
# Change only if you've changed the coordinator address or port.
coordinatorUrl: http://localhost:3442
# Api key obtained on https://rapidapi.com (go to MyApps -> Add New App -> Enter Name -> Application key)
rapidApiKey: 4UrKpcWXcxxxxxxxxxxxxxxp1Q8kI6jsn32xxxoVWiY7
# https://locationiq.com api key (register and you will receive the token in the email).
# Used only for .time command.
locationIqApiKey:
# https://timezonedb.com api key (register and you will receive the token in the email).
# Used only for .time command
timezoneDbApiKey:
# https://pro.coinmarketcap.com/account/ api key. There is a free plan for personal use.
# Used for cryptocurrency related commands.
coinmarketcapApiKey:
# Api key used for Osu related commands. Obtain this key at https://osu.ppy.sh/p/api
osuApiKey: 4c8c8fdffdsfdsfsdfsfa33f3f3140a7d93320d6
# Command and args which will be used to restart the bot.
# Only used if bot is executed directly (NOT through the coordinator)
# placeholders:
# {0} -> shard id
# {1} -> total shards
# Linux default
# cmd: dotnet
# args: "NadekoBot.dll -- {0}"
# Windows default
# cmd: NadekoBot.exe
# args: {0}
restartCommand:
cmd:
args:
``` ```
--- ---
@@ -121,13 +170,13 @@ For Windows (Source), Linux or OSX, add this to your `creds.yml`
Nadeko saves all settings and data in the database file `NadekoBot.db`, located in: Nadeko saves all settings and data in the database file `NadekoBot.db`, located in:
- Windows (Updater): `system/data` (can be easily accessed through the `Data` button on the updater) - Windows (Updater): `system/data` (can be easily accessed through the `Data` button on the updater)
- Windows (Source), Linux and OSX: `NadekoBot/src/NadekoBot/bin/Release/netcoreapp2.1/data/NadekoBot.db` - Windows (Source), Linux and OSX: `nadekobot/output/data/NadekoBot.db`
In order to open it you will need [SQLite Browser](http://sqlitebrowser.org/). In order to open it you will need [SQLite Browser](http://sqlitebrowser.org/).
*NOTE: You don't have to worry if you don't have the `NadekoBot.db` file, it gets automatically created once you successfully run the bot for the first time.* *NOTE: You don't have to worry if you don't have the `NadekoBot.db` file, it gets automatically created once you successfully run the bot for the first time.*
**To make changes:** **To make changes to the database on windows:**
- Shut your bot down. - Shut your bot down.
- Copy the `NadekoBot.db` file to someplace safe. (Back up) - Copy the `NadekoBot.db` file to someplace safe. (Back up)
@@ -146,20 +195,24 @@ In order to open it you will need [SQLite Browser](http://sqlitebrowser.org/).
## Sharding your bot ## Sharding your bot
- **ShardRunCommand** To run a sharded bot, you will want to run `src/NadekoBot.Coordinator` project.
- Command with which to run shards 1+ Shards communicate with the coordinator using gRPC
- Required if you're sharding your bot on windows using .exe, or in a custom way. To configure your Coordinator, you will need to edit the `src/NadekoBot.Coordinator/coord.yml` file
- This internally defaults to `dotnet`
- For example, if you want to shard your NadekoBot which you installed using windows installer, you would want to set it to something like this: `C:\Program Files\NadekoBot\system\NadekoBot.exe` ```yml
- **ShardRunArguments** # total number of shards
- Arguments to the shard run command TotalShards: 3
- Required if you're sharding your bot on windows using .exe, or in a custom way. # How often do shards ping their state back to the coordinator
- This internally defaults to `run -c Release --no-build -- {0} {1} {2}` which will be enough to run linux and other 'from source' setups RecheckIntervalMs: 5000
- {0} will be replaced by the `shard ID` of the shard being ran, {1} by the shard 0's process id, and {2} by the port shard communication is happening on # Command to run the shard
- If shard0 (main window) is closed, all other shards will close too ShardStartCommand: dotnet
- For example, if you want to shard your NadekoBot which you installed using windows installer, you would want to set it to `{0} {1} {2}` # Arguments to run the shard
- **ShardRunPort** # {0} = shard id
- Bot uses a random UDP port in [5000, 6000] range for communication between shards # {1} = total number of shards
ShardStartArgs: ../../output/NadekoBot.dll -- {0} {1}
# How long does it take for the shard to be forcefully restarted once it stops reporting its state
UnresponsiveSec: 30
```
[Google Console]: https://console.developers.google.com [Google Console]: https://console.developers.google.com
[DiscordApp]: https://discordapp.com/developers/applications/me [DiscordApp]: https://discordapp.com/developers/applications/me

View File

@@ -76,7 +76,6 @@ nav:
- Windows Guide: guides/windows-guide.md - Windows Guide: guides/windows-guide.md
- Linux Guide: guides/linux-guide.md - Linux Guide: guides/linux-guide.md
- OSX Guide: guides/osx-guide.md - OSX Guide: guides/osx-guide.md
- From Source: guides/from-source.md
- Docker Guide (unsupported): guides/docker-guide.md - Docker Guide (unsupported): guides/docker-guide.md
- Commands: - Commands:
- Readme: commands-readme.md - Readme: commands-readme.md

View File

@@ -1,5 +1,12 @@
# total number of shards
TotalShards: 3 TotalShards: 3
# How often do shards ping their state back to the coordinator
RecheckIntervalMs: 5000 RecheckIntervalMs: 5000
# Command to run the shard
ShardStartCommand: dotnet ShardStartCommand: dotnet
# Arguments to run the shard
# {0} = shard id
# {1} = total number of shards
ShardStartArgs: run -p "..\NadekoBot\NadekoBot.csproj" --no-build -- {0} {1} ShardStartArgs: run -p "..\NadekoBot\NadekoBot.csproj" --no-build -- {0} {1}
# How long does it take for the shard to be forcefully restarted once it stops reporting its state
UnresponsiveSec: 30 UnresponsiveSec: 30

View File

@@ -113,33 +113,15 @@ namespace NadekoBot.Db
return config; return config;
} }
public static GuildConfig LogSettingsFor(this NadekoContext ctx, ulong guildId) public static LogSetting LogSettingsFor(this NadekoContext ctx, ulong guildId)
{ {
var config = ctx var logSetting = ctx.LogSettings
.GuildConfigs
.AsQueryable() .AsQueryable()
.Include(gc => gc.LogSetting) .Include(x => x.IgnoredChannels)
.ThenInclude(gc => gc.IgnoredChannels) .Where(x => x.GuildId == guildId)
.FirstOrDefault(x => x.GuildId == guildId); .FirstOrDefault();
if (config is null) return logSetting;
{
ctx.GuildConfigs.Add((config = new GuildConfig
{
GuildId = guildId,
Permissions = Permissionv2.GetDefaultPermlist,
WarningsInitialized = true,
WarnPunishments = DefaultWarnPunishments,
}));
ctx.SaveChanges();
}
if (!config.WarningsInitialized)
{
config.WarningsInitialized = true;
config.WarnPunishments = DefaultWarnPunishments;
}
return config;
} }
public static IEnumerable<GuildConfig> Permissionsv2ForAll(this DbSet<GuildConfig> configs, List<ulong> include) public static IEnumerable<GuildConfig> Permissionsv2ForAll(this DbSet<GuildConfig> configs, List<ulong> include)

View File

@@ -29,11 +29,18 @@ namespace NadekoBot.Services.Database.Models
public bool SendChannelGreetMessage { get; set; } public bool SendChannelGreetMessage { get; set; }
public string ChannelGreetMessageText { get; set; } = "Welcome to the %server% server, %user%!"; public string ChannelGreetMessageText { get; set; } = "Welcome to the %server% server, %user%!";
#region Boost Message
public bool SendBoostMessage { get; set; }
public string BoostMessage { get; set; } = "%user% just boosted this server!";
public ulong BoostMessageChannelId { get; set; }
public int BoostMessageDeleteAfter { get; set; }
#endregion
public bool SendChannelByeMessage { get; set; } public bool SendChannelByeMessage { get; set; }
public string ChannelByeMessageText { get; set; } = "%user% has left!"; public string ChannelByeMessageText { get; set; } = "%user% has left!";
public LogSetting LogSetting { get; set; } = new LogSetting();
//self assignable roles //self assignable roles
public bool ExclusiveSelfAssignedRoles { get; set; } public bool ExclusiveSelfAssignedRoles { get; set; }
public bool AutoDeleteSelfAssignedRoleMessages { get; set; } public bool AutoDeleteSelfAssignedRoleMessages { get; set; }

View File

@@ -8,6 +8,7 @@ namespace NadekoBot.Services.Database.Models
public HashSet<IgnoredLogChannel> IgnoredChannels { get; set; } = new HashSet<IgnoredLogChannel>(); public HashSet<IgnoredLogChannel> IgnoredChannels { get; set; } = new HashSet<IgnoredLogChannel>();
public HashSet<IgnoredVoicePresenceChannel> IgnoredVoicePresenceChannelIds { get; set; } = new HashSet<IgnoredVoicePresenceChannel>(); public HashSet<IgnoredVoicePresenceChannel> IgnoredVoicePresenceChannelIds { get; set; } = new HashSet<IgnoredVoicePresenceChannel>();
public ulong GuildId { get; set; }
public ulong? LogOtherId { get; set; } public ulong? LogOtherId { get; set; }
public ulong? MessageUpdatedId { get; set; } public ulong? MessageUpdatedId { get; set; }
public ulong? MessageDeletedId { get; set; } public ulong? MessageDeletedId { get; set; }

View File

@@ -328,6 +328,23 @@ namespace NadekoBot.Services.Database
.HasDefaultValue(100); .HasDefaultValue(100);
#endregion #endregion
#region Reaction roles
modelBuilder.Entity<ReactionRoleMessage>(rrm => rrm
.HasMany(x => x.ReactionRoles)
.WithOne()
.OnDelete(DeleteBehavior.Cascade));
#endregion
#region LogSettings
modelBuilder.Entity<LogSetting>(ls => ls
.HasIndex(x => x.GuildId)
.IsUnique());
#endregion
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations
{
public partial class rerocascade : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ReactionRole_ReactionRoleMessage_ReactionRoleMessageId",
table: "ReactionRole");
migrationBuilder.AddForeignKey(
name: "FK_ReactionRole_ReactionRoleMessage_ReactionRoleMessageId",
table: "ReactionRole",
column: "ReactionRoleMessageId",
principalTable: "ReactionRoleMessage",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ReactionRole_ReactionRoleMessage_ReactionRoleMessageId",
table: "ReactionRole");
migrationBuilder.AddForeignKey(
name: "FK_ReactionRole_ReactionRoleMessage_ReactionRoleMessageId",
table: "ReactionRole",
column: "ReactionRoleMessageId",
principalTable: "ReactionRoleMessage",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,56 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations
{
public partial class boostmessages : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BoostMessage",
table: "GuildConfigs",
type: "TEXT",
nullable: true);
migrationBuilder.AddColumn<ulong>(
name: "BoostMessageChannelId",
table: "GuildConfigs",
type: "INTEGER",
nullable: false,
defaultValue: 0ul);
migrationBuilder.AddColumn<int>(
name: "BoostMessageDeleteAfter",
table: "GuildConfigs",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<bool>(
name: "SendBoostMessage",
table: "GuildConfigs",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BoostMessage",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "BoostMessageChannelId",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "BoostMessageDeleteAfter",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "SendBoostMessage",
table: "GuildConfigs");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,69 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations
{
public partial class logsettingsindependence : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<ulong>(
name: "GuildId",
table: "LogSettings",
type: "INTEGER",
nullable: false,
defaultValue: 0ul);
migrationBuilder.Sql(
@"UPDATE LogSettings SET GuildId = (SELECT GuildId FROM GuildConfigs WHERE LogSettingId = LogSettings.Id);
DELETE FROM LogSettings WHERE GuildId = 0;");
migrationBuilder.DropForeignKey(
name: "FK_GuildConfigs_LogSettings_LogSettingId",
table: "GuildConfigs");
migrationBuilder.DropIndex(
name: "IX_GuildConfigs_LogSettingId",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "LogSettingId",
table: "GuildConfigs");
migrationBuilder.CreateIndex(
name: "IX_LogSettings_GuildId",
table: "LogSettings",
column: "GuildId",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_LogSettings_GuildId",
table: "LogSettings");
migrationBuilder.DropColumn(
name: "GuildId",
table: "LogSettings");
migrationBuilder.AddColumn<int>(
name: "LogSettingId",
table: "GuildConfigs",
type: "INTEGER",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_GuildConfigs_LogSettingId",
table: "GuildConfigs",
column: "LogSettingId");
migrationBuilder.AddForeignKey(
name: "FK_GuildConfigs_LogSettings_LogSettingId",
table: "GuildConfigs",
column: "LogSettingId",
principalTable: "LogSettings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}

View File

@@ -14,7 +14,7 @@ namespace NadekoBot.Migrations
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "5.0.7"); .HasAnnotation("ProductVersion", "5.0.8");
modelBuilder.Entity("NadekoBot.Db.Models.ClubApplicants", b => modelBuilder.Entity("NadekoBot.Db.Models.ClubApplicants", b =>
{ {
@@ -741,6 +741,15 @@ namespace NadekoBot.Migrations
b.Property<bool>("AutoDeleteSelfAssignedRoleMessages") b.Property<bool>("AutoDeleteSelfAssignedRoleMessages")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<string>("BoostMessage")
.HasColumnType("TEXT");
b.Property<ulong>("BoostMessageChannelId")
.HasColumnType("INTEGER");
b.Property<int>("BoostMessageDeleteAfter")
.HasColumnType("INTEGER");
b.Property<ulong>("ByeMessageChannelId") b.Property<ulong>("ByeMessageChannelId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -786,9 +795,6 @@ namespace NadekoBot.Migrations
b.Property<string>("Locale") b.Property<string>("Locale")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<int?>("LogSettingId")
.HasColumnType("INTEGER");
b.Property<string>("MuteRoleName") b.Property<string>("MuteRoleName")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -801,6 +807,9 @@ namespace NadekoBot.Migrations
b.Property<string>("Prefix") b.Property<string>("Prefix")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<bool>("SendBoostMessage")
.HasColumnType("INTEGER");
b.Property<bool>("SendChannelByeMessage") b.Property<bool>("SendChannelByeMessage")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -833,8 +842,6 @@ namespace NadekoBot.Migrations
b.HasIndex("GuildId") b.HasIndex("GuildId")
.IsUnique(); .IsUnique();
b.HasIndex("LogSettingId");
b.HasIndex("WarnExpireHours"); b.HasIndex("WarnExpireHours");
b.ToTable("GuildConfigs"); b.ToTable("GuildConfigs");
@@ -902,6 +909,9 @@ namespace NadekoBot.Migrations
b.Property<DateTime?>("DateAdded") b.Property<DateTime?>("DateAdded")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<ulong>("GuildId")
.HasColumnType("INTEGER");
b.Property<ulong?>("LogOtherId") b.Property<ulong?>("LogOtherId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -940,6 +950,9 @@ namespace NadekoBot.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("GuildId")
.IsUnique();
b.ToTable("LogSettings"); b.ToTable("LogSettings");
}); });
@@ -2233,15 +2246,6 @@ namespace NadekoBot.Migrations
b.Navigation("GuildConfig"); b.Navigation("GuildConfig");
}); });
modelBuilder.Entity("NadekoBot.Services.Database.Models.GuildConfig", b =>
{
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
.WithMany()
.HasForeignKey("LogSettingId");
b.Navigation("LogSetting");
});
modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b => modelBuilder.Entity("NadekoBot.Services.Database.Models.IgnoredLogChannel", b =>
{ {
b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting") b.HasOne("NadekoBot.Services.Database.Models.LogSetting", "LogSetting")
@@ -2307,7 +2311,8 @@ namespace NadekoBot.Migrations
{ {
b.HasOne("NadekoBot.Services.Database.Models.ReactionRoleMessage", null) b.HasOne("NadekoBot.Services.Database.Models.ReactionRoleMessage", null)
.WithMany("ReactionRoles") .WithMany("ReactionRoles")
.HasForeignKey("ReactionRoleMessageId"); .HasForeignKey("ReactionRoleMessageId")
.OnDelete(DeleteBehavior.Cascade);
}); });
modelBuilder.Entity("NadekoBot.Services.Database.Models.ReactionRoleMessage", b => modelBuilder.Entity("NadekoBot.Services.Database.Models.ReactionRoleMessage", b =>

View File

@@ -27,13 +27,13 @@ namespace NadekoBot.Modules.Administration
_services = services; _services = services;
} }
public async Task InternalReactionRoles(bool exclusive, params string[] input) public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input)
{ {
var msgs = await ((SocketTextChannel)ctx.Channel).GetMessagesAsync().FlattenAsync().ConfigureAwait(false); var target = messageId is ulong msgId
var prev = (IUserMessage)msgs.FirstOrDefault(x => x is IUserMessage && x.Id != ctx.Message.Id); ? await ctx.Channel.GetMessageAsync(msgId).ConfigureAwait(false)
: (await ctx.Channel.GetMessagesAsync(2).FlattenAsync().ConfigureAwait(false))
if (prev is null) .Skip(1)
return; .FirstOrDefault();
if (input.Length % 2 != 0) if (input.Length % 2 != 0)
return; return;
@@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Administration
{ {
try try
{ {
await prev.AddReactionAsync(x.emote, new RequestOptions() await target.AddReactionAsync(x.emote, new RequestOptions()
{ {
RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit
}).ConfigureAwait(false); }).ConfigureAwait(false);
@@ -86,8 +86,8 @@ namespace NadekoBot.Modules.Administration
if (_service.Add(ctx.Guild.Id, new ReactionRoleMessage() if (_service.Add(ctx.Guild.Id, new ReactionRoleMessage()
{ {
Exclusive = exclusive, Exclusive = exclusive,
MessageId = prev.Id, MessageId = target.Id,
ChannelId = prev.Channel.Id, ChannelId = target.Channel.Id,
ReactionRoles = all.Select(x => ReactionRoles = all.Select(x =>
{ {
return new ReactionRole() return new ReactionRole()
@@ -106,6 +106,24 @@ namespace NadekoBot.Modules.Administration
} }
} }
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
[NoPublicBot]
[UserPerm(GuildPerm.ManageRoles)]
[BotPerm(GuildPerm.ManageRoles)]
[Priority(0)]
public Task ReactionRoles(ulong messageId, params string[] input) =>
InternalReactionRoles(false, messageId, input);
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
[NoPublicBot]
[UserPerm(GuildPerm.ManageRoles)]
[BotPerm(GuildPerm.ManageRoles)]
[Priority(1)]
public Task ReactionRoles(ulong messageId, Exclude _, params string[] input) =>
InternalReactionRoles(true, messageId, input);
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[NoPublicBot] [NoPublicBot]
@@ -113,7 +131,7 @@ namespace NadekoBot.Modules.Administration
[BotPerm(GuildPerm.ManageRoles)] [BotPerm(GuildPerm.ManageRoles)]
[Priority(0)] [Priority(0)]
public Task ReactionRoles(params string[] input) => public Task ReactionRoles(params string[] input) =>
InternalReactionRoles(false, input); InternalReactionRoles(false, null, input);
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
@@ -122,7 +140,7 @@ namespace NadekoBot.Modules.Administration
[BotPerm(GuildPerm.ManageRoles)] [BotPerm(GuildPerm.ManageRoles)]
[Priority(1)] [Priority(1)]
public Task ReactionRoles(Exclude _, params string[] input) => public Task ReactionRoles(Exclude _, params string[] input) =>
InternalReactionRoles(true, input); InternalReactionRoles(true, null, input);
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]

View File

@@ -12,6 +12,53 @@ namespace NadekoBot.Modules.Administration
[Group] [Group]
public class ServerGreetCommands : NadekoSubmodule<GreetSettingsService> public class ServerGreetCommands : NadekoSubmodule<GreetSettingsService>
{ {
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageGuild)]
public async Task Boost()
{
var enabled = await _service.ToggleBoost(ctx.Guild.Id, ctx.Channel.Id);
if (enabled)
await ReplyConfirmLocalizedAsync(strs.boost_on).ConfigureAwait(false);
else
await ReplyPendingLocalizedAsync(strs.boost_off).ConfigureAwait(false);
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageGuild)]
public async Task BoostDel(int timer = 30)
{
if (timer < 0 || timer > 600)
return;
await _service.SetBoostDel(ctx.Guild.Id, timer);
if (timer > 0)
await ReplyConfirmLocalizedAsync(strs.boostdel_on(timer));
else
await ReplyPendingLocalizedAsync(strs.boostdel_off).ConfigureAwait(false);
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageGuild)]
public async Task BoostMsg([Leftover] string text)
{
if (string.IsNullOrWhiteSpace(text))
{
await GreetMsg().ConfigureAwait(false);
return;
}
var sendBoostEnabled = _service.SetBoostMessage(ctx.Guild.Id, ref text);
await ReplyConfirmLocalizedAsync(strs.boostmsg_new).ConfigureAwait(false);
if (!sendBoostEnabled)
await ReplyPendingLocalizedAsync(strs.boostmsg_enable($"`{Prefix}boost`"));
}
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageGuild)] [UserPerm(GuildPerm.ManageGuild)]
@@ -23,9 +70,9 @@ namespace NadekoBot.Modules.Administration
await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false); await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false);
if (timer > 0) if (timer > 0)
await ReplyErrorLocalizedAsync(strs.greetdel_on(timer)); await ReplyConfirmLocalizedAsync(strs.greetdel_on(timer));
else else
await ReplyConfirmLocalizedAsync(strs.greetdel_off).ConfigureAwait(false); await ReplyPendingLocalizedAsync(strs.greetdel_off).ConfigureAwait(false);
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -38,7 +85,7 @@ namespace NadekoBot.Modules.Administration
if (enabled) if (enabled)
await ReplyConfirmLocalizedAsync(strs.greet_on).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.greet_on).ConfigureAwait(false);
else else
await ReplyConfirmLocalizedAsync(strs.greet_off).ConfigureAwait(false); await ReplyPendingLocalizedAsync(strs.greet_off).ConfigureAwait(false);
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -46,8 +93,8 @@ namespace NadekoBot.Modules.Administration
[UserPerm(GuildPerm.ManageGuild)] [UserPerm(GuildPerm.ManageGuild)]
public Task GreetMsg() public Task GreetMsg()
{ {
string greetMsg = _service.GetGreetMsg(ctx.Guild.Id); var greetMsg = _service.GetGreetMsg(ctx.Guild.Id);
return ReplyErrorLocalizedAsync(strs.greetmsg_cur(greetMsg?.SanitizeMentions())); return ReplyConfirmLocalizedAsync(strs.greetmsg_cur(greetMsg?.SanitizeMentions()));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -65,7 +112,7 @@ namespace NadekoBot.Modules.Administration
await ReplyConfirmLocalizedAsync(strs.greetmsg_new).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.greetmsg_new).ConfigureAwait(false);
if (!sendGreetEnabled) if (!sendGreetEnabled)
await ReplyErrorLocalizedAsync(strs.greetmsg_enable($"`{Prefix}greet`")); await ReplyPendingLocalizedAsync(strs.greetmsg_enable($"`{Prefix}greet`"));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -87,7 +134,7 @@ namespace NadekoBot.Modules.Administration
public Task GreetDmMsg() public Task GreetDmMsg()
{ {
var dmGreetMsg = _service.GetDmGreetMsg(ctx.Guild.Id); var dmGreetMsg = _service.GetDmGreetMsg(ctx.Guild.Id);
return ReplyErrorLocalizedAsync(strs.greetdmmsg_cur(dmGreetMsg?.SanitizeMentions())); return ReplyConfirmLocalizedAsync(strs.greetdmmsg_cur(dmGreetMsg?.SanitizeMentions()));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -105,7 +152,7 @@ namespace NadekoBot.Modules.Administration
await ReplyConfirmLocalizedAsync(strs.greetdmmsg_new).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.greetdmmsg_new).ConfigureAwait(false);
if (!sendGreetEnabled) if (!sendGreetEnabled)
await ReplyErrorLocalizedAsync(strs.greetdmmsg_enable($"`{Prefix}greetdm`")); await ReplyPendingLocalizedAsync(strs.greetdmmsg_enable($"`{Prefix}greetdm`"));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -127,7 +174,7 @@ namespace NadekoBot.Modules.Administration
public Task ByeMsg() public Task ByeMsg()
{ {
var byeMsg = _service.GetByeMessage(ctx.Guild.Id); var byeMsg = _service.GetByeMessage(ctx.Guild.Id);
return ReplyErrorLocalizedAsync(strs.byemsg_cur(byeMsg?.SanitizeMentions())); return ReplyConfirmLocalizedAsync(strs.byemsg_cur(byeMsg?.SanitizeMentions()));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -145,7 +192,7 @@ namespace NadekoBot.Modules.Administration
await ReplyConfirmLocalizedAsync(strs.byemsg_new).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.byemsg_new).ConfigureAwait(false);
if (!sendByeEnabled) if (!sendByeEnabled)
await ReplyErrorLocalizedAsync(strs.byemsg_enable($"`{Prefix}bye`")); await ReplyPendingLocalizedAsync(strs.byemsg_enable($"`{Prefix}bye`"));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
@@ -156,9 +203,9 @@ namespace NadekoBot.Modules.Administration
await _service.SetByeDel(ctx.Guild.Id, timer).ConfigureAwait(false); await _service.SetByeDel(ctx.Guild.Id, timer).ConfigureAwait(false);
if (timer > 0) if (timer > 0)
await ReplyErrorLocalizedAsync(strs.byedel_on(timer)); await ReplyConfirmLocalizedAsync(strs.byedel_on(timer));
else else
await ReplyConfirmLocalizedAsync(strs.byedel_off).ConfigureAwait(false); await ReplyPendingLocalizedAsync(strs.byedel_off).ConfigureAwait(false);
} }
@@ -174,7 +221,7 @@ namespace NadekoBot.Modules.Administration
var enabled = _service.GetByeEnabled(ctx.Guild.Id); var enabled = _service.GetByeEnabled(ctx.Guild.Id);
if (!enabled) if (!enabled)
{ {
await ReplyErrorLocalizedAsync(strs.byemsg_enable($"`{Prefix}bye`")); await ReplyPendingLocalizedAsync(strs.byemsg_enable($"`{Prefix}bye`"));
} }
} }
@@ -190,7 +237,7 @@ namespace NadekoBot.Modules.Administration
var enabled = _service.GetGreetEnabled(ctx.Guild.Id); var enabled = _service.GetGreetEnabled(ctx.Guild.Id);
if (!enabled) if (!enabled)
{ {
await ReplyErrorLocalizedAsync(strs.greetmsg_enable($"`{Prefix}greet`")); await ReplyPendingLocalizedAsync(strs.greetmsg_enable($"`{Prefix}greet`"));
} }
} }
@@ -210,7 +257,7 @@ namespace NadekoBot.Modules.Administration
await ctx.WarningAsync(); await ctx.WarningAsync();
var enabled = _service.GetGreetDmEnabled(ctx.Guild.Id); var enabled = _service.GetGreetDmEnabled(ctx.Guild.Id);
if (!enabled) if (!enabled)
await ReplyErrorLocalizedAsync(strs.greetdmmsg_enable($"`{Prefix}greetdm`")); await ReplyPendingLocalizedAsync(strs.greetdmmsg_enable($"`{Prefix}greetdm`"));
} }
} }
} }

View File

@@ -93,15 +93,15 @@ namespace NadekoBot.Modules.Administration.Services
{ {
var guildIds = client.Guilds.Select(x => x.Id).ToList(); var guildIds = client.Guilds.Select(x => x.Id).ToList();
var configs = uow var configs = uow
.Set<GuildConfig>() .LogSettings
.AsQueryable() .AsQueryable()
.Include(gc => gc.LogSetting) .AsNoTracking()
.ThenInclude(ls => ls.IgnoredChannels)
.Where(x => guildIds.Contains(x.GuildId)) .Where(x => guildIds.Contains(x.GuildId))
.Include(ls => ls.IgnoredChannels)
.ToList(); .ToList();
GuildLogSettings = configs GuildLogSettings = configs
.ToDictionary(g => g.GuildId, g => g.LogSetting) .ToDictionary(ls => ls.GuildId)
.ToConcurrent(); .ToConcurrent();
} }
@@ -170,17 +170,15 @@ namespace NadekoBot.Modules.Administration.Services
int removed = 0; int removed = 0;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var config = uow.LogSettingsFor(gid); var logSetting = uow.LogSettingsFor(gid);
LogSetting logSetting = GuildLogSettings.GetOrAdd(gid, (id) => config.LogSetting);
removed = logSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == cid); removed = logSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == cid);
config.LogSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == cid);
if (removed == 0) if (removed == 0)
{ {
var toAdd = new IgnoredLogChannel {ChannelId = cid}; var toAdd = new IgnoredLogChannel {ChannelId = cid};
logSetting.IgnoredChannels.Add(toAdd); logSetting.IgnoredChannels.Add(toAdd);
config.LogSetting.IgnoredChannels.Add(toAdd);
} }
GuildLogSettings.AddOrUpdate(gid, logSetting, (_, _) => logSetting);
uow.SaveChanges(); uow.SaveChanges();
} }
@@ -209,11 +207,10 @@ namespace NadekoBot.Modules.Administration.Services
public async Task LogServer(ulong guildId, ulong channelId, bool value) public async Task LogServer(ulong guildId, ulong channelId, bool value)
{ {
LogSetting logSetting;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
logSetting = uow.LogSettingsFor(guildId).LogSetting; var logSetting = uow.LogSettingsFor(guildId);
GuildLogSettings.AddOrUpdate(guildId, (id) => logSetting, (id, old) => logSetting);
logSetting.LogOtherId = logSetting.LogOtherId =
logSetting.MessageUpdatedId = logSetting.MessageUpdatedId =
logSetting.MessageDeletedId = logSetting.MessageDeletedId =
@@ -230,8 +227,9 @@ namespace NadekoBot.Modules.Administration.Services
logSetting.UserMutedId = logSetting.UserMutedId =
logSetting.LogVoicePresenceTTSId = logSetting.LogVoicePresenceTTSId =
(value ? channelId : (ulong?) null); (value ? channelId : (ulong?) null);
;
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
GuildLogSettings.AddOrUpdate(guildId, (id) => logSetting, (id, old) => logSetting);
} }
} }
@@ -301,7 +299,7 @@ namespace NadekoBot.Modules.Administration.Services
ulong? channelId = null; ulong? channelId = null;
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var logSetting = uow.LogSettingsFor(gid).LogSetting; var logSetting = uow.LogSettingsFor(gid);
GuildLogSettings.AddOrUpdate(gid, (id) => logSetting, (id, old) => logSetting); GuildLogSettings.AddOrUpdate(gid, (id) => logSetting, (id, old) => logSetting);
switch (type) switch (type)
{ {
@@ -1238,7 +1236,7 @@ namespace NadekoBot.Modules.Administration.Services
{ {
using (var uow = _db.GetDbContext()) using (var uow = _db.GetDbContext())
{ {
var newLogSetting = uow.LogSettingsFor(guildId).LogSetting; var newLogSetting = uow.LogSettingsFor(guildId);
switch (logChannelType) switch (logChannelType)
{ {
case LogType.Other: case LogType.Other:

View File

@@ -8,6 +8,8 @@ using NadekoBot.Extensions;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using LinqToDB;
using LinqToDB.EntityFrameworkCore;
using NadekoBot.Db; using NadekoBot.Db;
using Serilog; using Serilog;
@@ -155,19 +157,23 @@ namespace NadekoBot.Modules.Administration.Services
public bool Add(ulong id, ReactionRoleMessage rrm) public bool Add(ulong id, ReactionRoleMessage rrm)
{ {
using (var uow = _db.GetDbContext()) using var uow = _db.GetDbContext();
{ var table = uow.GetTable<ReactionRoleMessage>();
table.Delete(x => x.MessageId == rrm.MessageId);
var gc = uow.GuildConfigsForId(id, set => set var gc = uow.GuildConfigsForId(id, set => set
.Include(x => x.ReactionRoleMessages) .Include(x => x.ReactionRoleMessages)
.ThenInclude(x => x.ReactionRoles)); .ThenInclude(x => x.ReactionRoles));
if (gc.ReactionRoleMessages.Count >= 10) if (gc.ReactionRoleMessages.Count >= 10)
return false; return false;
gc.ReactionRoleMessages.Add(rrm); gc.ReactionRoleMessages.Add(rrm);
uow.SaveChanges();
_models.AddOrUpdate(id, _models.AddOrUpdate(id,
gc.ReactionRoleMessages, gc.ReactionRoleMessages,
delegate { return gc.ReactionRoleMessages; }); delegate { return gc.ReactionRoleMessages; });
uow.SaveChanges();
}
return true; return true;
} }

View File

@@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Gambling
await _cs.AddAsync(ctx.User.Id, "Timely claim", val).ConfigureAwait(false); await _cs.AddAsync(ctx.User.Id, "Timely claim", val).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.timely(n(val) + CurrencySign, period)); await ReplyConfirmLocalizedAsync(strs.timely(n(val) + CurrencySign, period));
} }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]

View File

@@ -362,6 +362,14 @@ namespace NadekoBot.Modules.Help
if (!(serviceUrl is null || accessKey is null || secretAcccessKey is null)) if (!(serviceUrl is null || accessKey is null || secretAcccessKey is null))
{ {
var config = new AmazonS3Config {ServiceURL = serviceUrl}; var config = new AmazonS3Config {ServiceURL = serviceUrl};
using var dlClient = new AmazonS3Client(accessKey, secretAcccessKey, config);
var oldVersionObject = await dlClient.GetObjectAsync(new GetObjectRequest()
{
BucketName = "nadeko-pictures",
Key = "cmds/versions.json",
});
using (var client = new AmazonS3Client(accessKey, secretAcccessKey, config)) using (var client = new AmazonS3Client(accessKey, secretAcccessKey, config))
{ {
await client.PutObjectAsync(new PutObjectRequest() await client.PutObjectAsync(new PutObjectRequest()
@@ -375,10 +383,9 @@ namespace NadekoBot.Modules.Help
}); });
} }
const string cmdVersionsFilePath = "../../cmd-versions.json"; using var ms = new MemoryStream();
var versionListString = File.Exists(cmdVersionsFilePath) await oldVersionObject.ResponseStream.CopyToAsync(ms);
? await File.ReadAllTextAsync(cmdVersionsFilePath) var versionListString = Encoding.UTF8.GetString(ms.ToArray());
: "[]";
var versionList = System.Text.Json.JsonSerializer.Deserialize<List<string>>(versionListString); var versionList = System.Text.Json.JsonSerializer.Deserialize<List<string>>(versionListString);
if (!versionList.Contains(StatsService.BotVersion)) if (!versionList.Contains(StatsService.BotVersion))
@@ -391,7 +398,6 @@ namespace NadekoBot.Modules.Help
{ {
WriteIndented = true WriteIndented = true
}); });
await File.WriteAllTextAsync(cmdVersionsFilePath, versionListString);
// upload the updated version list // upload the updated version list
using var client = new AmazonS3Client(accessKey, secretAcccessKey, config); using var client = new AmazonS3Client(accessKey, secretAcccessKey, config);

View File

@@ -163,7 +163,7 @@ namespace NadekoBot.Modules.NSFW
{ {
if (!_service.AutoBoobTimers.TryRemove(ctx.Channel.Id, out t)) return; if (!_service.AutoBoobTimers.TryRemove(ctx.Channel.Id, out t)) return;
t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer t.Change(Timeout.Infinite, Timeout.Infinite);
await ReplyConfirmLocalizedAsync(strs.stopped).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.stopped).ConfigureAwait(false);
return; return;
} }

View File

@@ -16,33 +16,33 @@ namespace NadekoBot.Modules.Searches
[Group] [Group]
public class AnimeSearchCommands : NadekoSubmodule<AnimeSearchService> public class AnimeSearchCommands : NadekoSubmodule<AnimeSearchService>
{ {
[NadekoCommand, Aliases] // [NadekoCommand, Aliases]
public async Task Novel([Leftover] string query) // public async Task Novel([Leftover] string query)
{ // {
if (string.IsNullOrWhiteSpace(query)) // if (string.IsNullOrWhiteSpace(query))
return; // return;
//
var novelData = await _service.GetNovelData(query).ConfigureAwait(false); // var novelData = await _service.GetNovelData(query).ConfigureAwait(false);
//
if (novelData is null) // if (novelData is null)
{ // {
await ReplyErrorLocalizedAsync(strs.failed_finding_novel).ConfigureAwait(false); // await ReplyErrorLocalizedAsync(strs.failed_finding_novel).ConfigureAwait(false);
return; // return;
} // }
//
var embed = _eb.Create() // var embed = _eb.Create()
.WithOkColor() // .WithOkColor()
.WithDescription(novelData.Description.Replace("<br>", Environment.NewLine, StringComparison.InvariantCulture)) // .WithDescription(novelData.Description.Replace("<br>", Environment.NewLine, StringComparison.InvariantCulture))
.WithTitle(novelData.Title) // .WithTitle(novelData.Title)
.WithUrl(novelData.Link) // .WithUrl(novelData.Link)
.WithImageUrl(novelData.ImageUrl) // .WithImageUrl(novelData.ImageUrl)
.AddField(GetText(strs.authors), string.Join("\n", novelData.Authors), true) // .AddField(GetText(strs.authors), string.Join("\n", novelData.Authors), true)
.AddField(GetText(strs.status), novelData.Status, true) // .AddField(GetText(strs.status), novelData.Status, true)
.AddField(GetText(strs.genres), string.Join(" ", novelData.Genres.Any() ? novelData.Genres : new[] { "none" }), true) // .AddField(GetText(strs.genres), string.Join(" ", novelData.Genres.Any() ? novelData.Genres : new[] { "none" }), true)
.WithFooter($"{GetText(strs.score)} {novelData.Score}"); // .WithFooter($"{GetText(strs.score)} {novelData.Score}");
//
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); // await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
} // }
[NadekoCommand, Aliases] [NadekoCommand, Aliases]
[Priority(0)] [Priority(0)]

View File

@@ -50,7 +50,6 @@ namespace NadekoBot.Modules.Searches.Services
} }
} }
// todo fix novel
public async Task<NovelResult> GetNovelData(string query) public async Task<NovelResult> GetNovelData(string query)
{ {
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
@@ -59,7 +58,10 @@ namespace NadekoBot.Modules.Searches.Services
query = query.Replace(" ", "-", StringComparison.InvariantCulture); query = query.Replace(" ", "-", StringComparison.InvariantCulture);
try try
{ {
var link = "http://www.novelupdates.com/series/" + Uri.EscapeDataString(query.Replace("/", " ", StringComparison.InvariantCulture)); var link = "https://www.novelupdates.com/series/" + Uri.EscapeDataString(query
.Replace(" ", "-")
.Replace("/", " ")
);
link = link.ToLowerInvariant(); link = link.ToLowerInvariant();
var (ok, data) = await _cache.TryGetNovelDataAsync(link).ConfigureAwait(false); var (ok, data) = await _cache.TryGetNovelDataAsync(link).ConfigureAwait(false);
if (!ok) if (!ok)

View File

@@ -48,8 +48,56 @@ namespace NadekoBot.Services
bot.JoinedGuild += Bot_JoinedGuild; bot.JoinedGuild += Bot_JoinedGuild;
_client.LeftGuild += _client_LeftGuild; _client.LeftGuild += _client_LeftGuild;
_client.GuildMemberUpdated += ClientOnGuildMemberUpdated;
} }
private Task ClientOnGuildMemberUpdated(SocketGuildUser oldUser, SocketGuildUser newUser)
{
// if user is a new booster
// or boosted again the same server
if ((oldUser is { PremiumSince: null } && newUser is { PremiumSince: not null })
|| (oldUser?.PremiumSince is DateTimeOffset oldDate
&& newUser?.PremiumSince is DateTimeOffset newDate
&& newDate > oldDate))
{
var conf = GetOrAddSettingsForGuild(newUser.Guild.Id);
if (!conf.SendBoostMessage) return Task.CompletedTask;
_ = Task.Run(TriggerBoostMessage(conf, newUser));
}
return Task.CompletedTask;
}
private Func<Task> TriggerBoostMessage(GreetSettings conf, SocketGuildUser user) => async () =>
{
var channel = user.Guild.GetTextChannel(conf.BoostMessageChannelId);
if (channel is null)
return;
if (string.IsNullOrWhiteSpace(conf.BoostMessage))
return;
var toSend = SmartText.CreateFrom(conf.BoostMessage);
var rep = new ReplacementBuilder()
.WithDefault(user, channel, user.Guild, _client)
.Build();
try
{
var toDelete = await channel.SendAsync(rep.Replace(toSend));
if (conf.BoostMessageDeleteAfter > 0)
{
toDelete.DeleteAfter(conf.BoostMessageDeleteAfter);
}
}
catch (Exception ex)
{
Log.Error(ex, "Error sending boost message.");
}
};
private Task _client_LeftGuild(SocketGuild arg) private Task _client_LeftGuild(SocketGuild arg)
{ {
GuildConfigsCache.TryRemove(arg.Id, out _); GuildConfigsCache.TryRemove(arg.Id, out _);
@@ -524,6 +572,49 @@ namespace NadekoBot.Services
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
} }
public bool SetBoostMessage(ulong guildId, ref string message)
{
message = message?.SanitizeMentions();
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set);
conf.BoostMessage = message;
var toAdd = GreetSettings.Create(conf);
GuildConfigsCache.AddOrUpdate(guildId, toAdd,(_, _) => toAdd);
uow.SaveChanges();
return conf.SendBoostMessage;
}
public async Task SetBoostDel(ulong guildId, int timer)
{
if (timer < 0 || timer > 600)
throw new ArgumentOutOfRangeException(nameof(timer));
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set);
conf.BoostMessageDeleteAfter = timer;
var toAdd = GreetSettings.Create(conf);
GuildConfigsCache.AddOrUpdate(guildId, toAdd,(_, _) => toAdd);
await uow.SaveChangesAsync();
}
public async Task<bool> ToggleBoost(ulong guildId, ulong channelId)
{
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set);
conf.SendBoostMessage = !conf.SendBoostMessage;
conf.BoostMessageChannelId = channelId;
await uow.SaveChangesAsync();
var toAdd = GreetSettings.Create(conf);
GuildConfigsCache.AddOrUpdate(guildId, toAdd,(_, _) => toAdd);
return conf.SendBoostMessage;
}
} }
public class GreetSettings public class GreetSettings
@@ -543,6 +634,11 @@ namespace NadekoBot.Services
public bool SendChannelByeMessage { get; set; } public bool SendChannelByeMessage { get; set; }
public string ChannelByeMessageText { get; set; } public string ChannelByeMessageText { get; set; }
public bool SendBoostMessage { get; set; }
public string BoostMessage { get; set; }
public int BoostMessageDeleteAfter { get; set; }
public ulong BoostMessageChannelId { get; set; }
public static GreetSettings Create(GuildConfig g) => new GreetSettings() public static GreetSettings Create(GuildConfig g) => new GreetSettings()
{ {
AutoDeleteByeMessagesTimer = g.AutoDeleteByeMessagesTimer, AutoDeleteByeMessagesTimer = g.AutoDeleteByeMessagesTimer,
@@ -555,6 +651,11 @@ namespace NadekoBot.Services
ChannelGreetMessageText = g.ChannelGreetMessageText, ChannelGreetMessageText = g.ChannelGreetMessageText,
SendChannelByeMessage = g.SendChannelByeMessage, SendChannelByeMessage = g.SendChannelByeMessage,
ChannelByeMessageText = g.ChannelByeMessageText, ChannelByeMessageText = g.ChannelByeMessageText,
SendBoostMessage = g.SendBoostMessage,
BoostMessage = g.BoostMessage,
BoostMessageDeleteAfter = g.BoostMessageDeleteAfter,
BoostMessageChannelId = g.BoostMessageChannelId
}; };
} }
} }

View File

@@ -10,7 +10,6 @@ using Serilog;
namespace NadekoBot.Services namespace NadekoBot.Services
{ {
// todo check why is memory usage so unstable
public sealed class BotCredsProvider public sealed class BotCredsProvider
{ {
private readonly int? _totalShards; private readonly int? _totalShards;

View File

@@ -12,8 +12,6 @@ using NadekoBot.Modules.Administration;
namespace NadekoBot.Services namespace NadekoBot.Services
{ {
// todo future use guild locale more in the code (from guild settings) (for dates, currency, etc?) // todo future use guild locale more in the code (from guild settings) (for dates, currency, etc?)
// todo future maybe Write a sourcegen for response strings
// and use const/static fields (maybe even typed to enforce correct number of arguments)
public class Localization : ILocalization, INService public class Localization : ILocalization, INService
{ {
private readonly BotConfigService _bss; private readonly BotConfigService _bss;

View File

@@ -19,7 +19,7 @@ namespace NadekoBot.Services
private readonly IBotCredentials _creds; private readonly IBotCredentials _creds;
private readonly DateTime _started; private readonly DateTime _started;
public const string BotVersion = "3.0.0"; public const string BotVersion = "3.0.2";
public string Author => "Kwoth#2452"; public string Author => "Kwoth#2452";
public string Library => "Discord.Net"; public string Library => "Discord.Net";

View File

@@ -32,6 +32,12 @@ greetdmtest:
- greetdmtest - greetdmtest
byetest: byetest:
- byetest - byetest
boost:
- boost
boostmsg:
- boostmsg
boostdel:
- boostdel
logserver: logserver:
- logserver - logserver
logignore: logignore:
@@ -1181,8 +1187,6 @@ timely:
- timely - timely
timelyreset: timelyreset:
- timelyreset - timelyreset
novel:
- novel
crypto: crypto:
- crypto - crypto
- c - c

View File

@@ -31,7 +31,12 @@ greet:
args: args:
- "" - ""
greetmsg: greetmsg:
desc: "Sets a new join announcement message which will be shown in the server's channel. Type `%user.mention%` if you want to mention the new member. Using it with no message will show the current greet message. You can use embed json from <https://eb.nadeko.bot/> instead of a regular text, if you want the message to be embedded." desc: |-
Sets a new join announcement message which will be shown in the server's channel.
Type `%user.mention%` if you want to mention the new member.
Full list of placeholders can be found here <https://nadekobot.readthedocs.io/en/latest/placeholders/>
Using it with no message will show the current greet message.
You can use embed json from <https://eb.nadeko.bot/> instead of a regular text, if you want the message to be embedded.
args: args:
- "Welcome, %user.mention%." - "Welcome, %user.mention%."
bye: bye:
@@ -39,7 +44,12 @@ bye:
args: args:
- "" - ""
byemsg: byemsg:
desc: "Sets a new leave announcement message. Type `%user.mention%` if you want to show the name the user who left. Type `%id%` to show id. Using this command with no message will show the current bye message. You can use embed json from <https://eb.nadeko.bot/> instead of a regular text, if you want the message to be embedded." desc: |-
Sets a new leave announcement message.
Type `%user.mention%` if you want to show the name the user who left.
Full list of placeholders can be found here <https://nadekobot.readthedocs.io/en/latest/placeholders/>
Using this command with no message will show the current bye message.
You can use embed json from <https://eb.nadeko.bot/> instead of a regular text, if you want the message to be embedded.
args: args:
- "%user.mention% has left." - "%user.mention% has left."
byedel: byedel:
@@ -66,6 +76,24 @@ byetest:
args: args:
- "" - ""
- "@SomeoneElse" - "@SomeoneElse"
boost:
desc: "Toggles anouncements on the current channel when someone boosts the server."
args:
- ""
boostmsg:
desc: |-
Sets a new boost announcement message.
Type `%user.mention%` if you want to show the name the user who left.
Full list of placeholders can be found here <https://nadekobot.readthedocs.io/en/latest/placeholders/>
Using this command with no message will show the current boost message.
You can use embed json from <https://eb.nadeko.bot/> instead of a regular text, if you want the message to be embedded.
args:
- "%user.mention% has boosted the server!!!"
boostdel:
desc: "Sets the time it takes (in seconds) for boost messages to be auto-deleted. Set it to `0` to disable automatic deletion."
args:
- "0"
- "30"
logserver: logserver:
desc: "Enables or Disables ALL log events. If enabled, all log events will log to this channel." desc: "Enables or Disables ALL log events. If enabled, all log events will log to this channel."
args: args:
@@ -1973,10 +2001,6 @@ timelyreset:
desc: "Resets all user timeouts on `{0}timely` command." desc: "Resets all user timeouts on `{0}timely` command."
args: args:
- "" - ""
novel:
desc: "Searches for a novel on `http://novelupdates.com/`. You have to provide an exact name."
args:
- "the nine cauldrons"
crypto: crypto:
desc: "Shows basic stats about a cryptocurrency from coinmarketcap.com. You can use either a name or an abbreviation of the currency." desc: "Shows basic stats about a cryptocurrency from coinmarketcap.com. You can use either a name or an abbreviation of the currency."
args: args:
@@ -2008,10 +2032,12 @@ rollduel:
- "50 @Someone" - "50 @Someone"
- "@Challenger" - "@Challenger"
reactionroles: reactionroles:
desc: "Specify role names and server emojis with which they're represented, the bot will then add those emojis to the previous message in the channel, and users will be able to get the roles by clicking on the emoji. You can set 'excl' as the first parameter to make them exclusive. You can have up to 5 of these enabled on one server at a time." desc: "Specify role names and server emojis with which they're represented, the bot will then add those emojis to the previous message in the channel, and users will be able to get the roles by clicking on the emoji. You can set 'excl' as the parameter before the reactions and roles to make them exclusive. You can have up to 5 of these enabled on one server at a time. Optionally you can specify target message if you don't want it to be the previous one."
args: args:
- "Gamer :SomeServerEmoji: Streamer :Other: Watcher :Other2:" - "Gamer :SomeServerEmoji: Streamer :Other: Watcher :Other2:"
- "excl Horde :Horde: Alliance :Alliance:" - "excl Horde :Horde: Alliance :Alliance:"
- "886382471732662332 excl Horde :Horde: Alliance :Alliance:"
- "886382471732662332 Gamer :SomeServerEmoji: Streamer :Other: Watcher :Other2:"
reactionroleslist: reactionroleslist:
desc: "Lists all ReactionRole messages on this channel and their indexes." desc: "Lists all ReactionRole messages on this channel and their indexes."
args: args:

File diff suppressed because it is too large Load Diff

View File

@@ -69,6 +69,13 @@
"greetmsg_new": "New greet message set.", "greetmsg_new": "New greet message set.",
"greet_off": "Greet announcements disabled.", "greet_off": "Greet announcements disabled.",
"greet_on": "Greet announcements enabled on this channel.", "greet_on": "Greet announcements enabled on this channel.",
"boost_on": "Boost announcements enabled on this channel.",
"boost_off": "Boost announcements disabled.",
"boostmsg_cur": "Current boost message: {0}",
"boostmsg_enable": "Enable boost messages by typing {0}",
"boostmsg_new": "New boost message set.",
"boostdel_off": "Automatic deletion of boost messages has been disabled.",
"boostdel_on": "Boost messages will be deleted after {0} seconds.",
"hierarchy": "You can't use this command on users with a role higher or equal than yours (or mine) in the role hierarchy.", "hierarchy": "You can't use this command on users with a role higher or equal than yours (or mine) in the role hierarchy.",
"role_too_high": "You can't use this command with roles which are above your highest role, unless you're server administrator.", "role_too_high": "You can't use this command with roles which are above your highest role, unless you're server administrator.",
"images_loading": "Images will be reloaded within a few seconds.", "images_loading": "Images will be reloaded within a few seconds.",