Compare commits

..

38 Commits

Author SHA1 Message Date
Kwoth
3f5443dd54 - Fixed .logevents and .log bugs related to thread logging
- Upped version to 4.3.16
- closes #418
2023-05-24 10:31:05 +02:00
Kwoth
93df4f3bf3 Upped version to 4.3.15, Updated CHANGELOG.md 2023-05-21 00:37:29 +02:00
Kwoth
073b832065 Fixed .rps 'amount' field, closes #415 2023-05-17 17:39:25 +02:00
Kwoth
a01e580e03 Merge branch 'hokutochen-v4-patch-69027' into 'v4'
%img:stuff% Deprecated

See merge request Kwoth/nadekobot!295
2023-05-07 16:14:48 +00:00
Hokuto Chen
6124e2fab5 %img:stuff% Deprecated 2023-05-07 16:14:48 +00:00
Kwoth
4dd31d6a0b Fixed .showembed, closes #410 2023-05-03 02:23:10 +02:00
Kwoth
e8706d4006 Fixed -w 0 for .trivia which allows for infinite games, closes #413 2023-05-02 09:36:27 +02:00
Kwoth
140cc43c98 Merge branch 'hokutochen-v4-patch-43149' into 'v4'
updated updater link

See merge request Kwoth/nadekobot!292
2023-04-06 00:40:30 +00:00
Hokuto Chen
26b7149435 updated updater link 2023-04-06 00:40:29 +00:00
Kwoth
b354ee7269 Merge branch 'v4' into 'v4'
fixed bank award giving error message instead of checkmark

See merge request Kwoth/nadekobot!294
2023-04-06 00:40:02 +00:00
Kamal Tufekcic
b829ca0109 fixed bank award giving error message instead of checkmark 2023-04-06 00:40:02 +00:00
Kwoth
37acdb81e8 Updated CHANGELOG.md, upped version to 4.3.14 2023-04-02 20:46:54 +02:00
Kwoth
a9aea65134 Possible fix for voice issues, thanks to anonymous contributor 2023-04-02 20:37:12 +02:00
Kwoth
5c03c5ba16 .banktake had ok/error responses flipped. No functional change, closes #409 2023-03-23 16:14:45 +01:00
Kwoth
42f00c08fa PermRole should deny messages in threads too, closes #407 2023-03-23 16:13:20 +01:00
Kwoth
598d3b8967 Merge branch 'v4' into 'v4'
Replaced CN API

See merge request Kwoth/nadekobot!291
2023-03-12 05:50:35 +00:00
Kamal Tufekcic
8df41c749b Replaced CN API 2023-03-12 05:50:35 +00:00
Kwoth
0eaa8be2d2 Merge branch 'v4' into 'v4'
Updated LMGTFY to be more offensive like before

See merge request Kwoth/nadekobot!289
2023-03-03 14:54:47 +00:00
Kamal Tufekcic
bdbe76f9f8 Update file Searches.cs 2023-03-03 14:21:59 +00:00
Kamal Tufekcic
08b609a4b4 Update file JokeCommands.cs 2023-02-28 19:50:52 +00:00
Snake26183
42d13b32b2 Merge branch 'v4' of https://gitlab.com/Kwoth/nadekobot into v4 2023-02-28 21:43:53 +00:00
Kwoth
096ada367f Cleanup 2023-02-28 14:49:50 +01:00
Kwoth
0fed33ebda Fixed .h <customeraction> not working with non-ascii characters 2023-02-28 13:22:44 +01:00
snake
cb9e918681 Merge branch 'v4' of https://gitlab.com/Kwoth/nadekobot into v4 2023-02-25 23:39:51 +02:00
Kwoth
bbf167df4d .logserver will now enable newer log events as well, closes #403 2023-02-22 14:43:29 +01:00
Kwoth
595a2b401c Merge branch 'v4' into 'v4'
Fixed incorrect `gpt.model` values, added ChatGPT to docs

See merge request Kwoth/nadekobot!287
2023-02-22 13:37:39 +00:00
Kamal Tufekcic
5713e8414e Fixed incorrect gpt.model values, added ChatGPT to docs 2023-02-22 13:37:39 +00:00
Kwoth
a551caf0da Merge branch 'hokutochen-v4-patch-39233' into 'v4'
removed 21.04 and 21.10 (EOL)

See merge request Kwoth/nadekobot!288
2023-02-21 20:42:14 +00:00
Hokuto Chen
b13f05c4c0 removed 21.04 and 21.10 (EOL) 2023-02-21 20:42:14 +00:00
Kwoth
6d6a3a811f Upped version to 4.2.13, updated changelog 2023-02-20 21:57:42 +01:00
Kwoth
fb4aac9f0d Fixed .log userpresence, closes #402 2023-02-20 21:53:25 +01:00
Kwoth
a98981de86 Changing the searches.yml ytprovider setting should now properly affect music queueing provider, but will require bot restart, closes #401 2023-02-20 02:12:00 +01:00
Kamal Tufekcic
9ef3646711 Update file config-guide.md 2023-02-13 12:26:21 +00:00
Kamal Tufekcic
9c174b8b6f Update file config-guide.md 2023-02-13 12:24:08 +00:00
Kamal Tufekcic
657c1e461c Update file config-guide.md 2023-02-13 12:01:33 +00:00
Kamal Tufekcic
f5a4a698bd Update file GamesConfig.cs 2023-02-13 11:52:33 +00:00
Kwoth
8112337aaf Merge branch 'hokutochen-v4-patch-25972' into 'v4'
fixed withURL not working

See merge request Kwoth/nadekobot!286
2023-02-12 10:20:22 +00:00
Hokuto Chen
73f7394e31 fixed withURL not working 2023-02-12 09:52:56 +00:00
27 changed files with 384 additions and 289 deletions

View File

@@ -2,7 +2,41 @@
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.12] - 11.02.2023 ## [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

View File

@@ -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*

View 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

View File

@@ -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

View File

@@ -89,6 +89,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)
![img](https://puu.sh/B7mgI.png) ![img](https://puu.sh/B7mgI.png)

View File

@@ -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)

View File

@@ -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;

View File

@@ -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;

View File

@@ -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);

View File

@@ -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);
} }

View File

@@ -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 { };

View File

@@ -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,70 @@ 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)
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 +167,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 +179,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 +230,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 +310,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 +329,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);
} }
@@ -307,18 +362,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.Discriminator} | {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 +455,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 +543,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 +590,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 +644,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 +697,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 +716,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 +724,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 +775,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 +824,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 +860,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)
{ {
@@ -942,11 +963,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 +996,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 +1037,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 +1081,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 +1135,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 +1195,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 +1272,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)

View File

@@ -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;
} }

View File

@@ -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();

View File

@@ -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]

View File

@@ -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),

View File

@@ -108,10 +108,10 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
public sealed partial class ChatGptConfig public sealed partial class ChatGptConfig
{ {
[Comment(@"Which GPT-3 Model should bot use. [Comment(@"Which GPT-3 Model should bot use.
'ada' - cheapest and fastest 'ada001' - cheapest and fastest
'babbage' - 2nd option 'babbage001' - 2nd option
'curie' - 3rd option 'curie001' - 3rd option
'davinci' - Most expensive, slowest")] 'davinci003' - Most expensive, slowest")]
public Gpt3Model Model { get; set; } = Gpt3Model.Ada001; public Gpt3Model Model { get; set; } = Gpt3Model.Ada001;
[Comment(@"The maximum number of tokens to use per GPT-3 API call")] [Comment(@"The maximum number of tokens to use per GPT-3 API call")]

View File

@@ -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);

View File

@@ -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;

View File

@@ -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)

View File

@@ -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;

View File

@@ -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,

View File

@@ -296,8 +296,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)

View File

@@ -550,15 +550,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]

View File

@@ -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.12"; public const string BOT_VERSION = "4.3.16";
public string Author public string Author
=> "Kwoth#2452"; => "Kwoth#2452";

View File

@@ -1559,7 +1559,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"

View File

@@ -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);