Skip to content

Commit

Permalink
Various cleanup items, updated encounter tables
Browse files Browse the repository at this point in the history
  • Loading branch information
ReefSnax committed Jul 14, 2024
1 parent 50a800e commit efb99ae
Show file tree
Hide file tree
Showing 78 changed files with 1,224 additions and 454 deletions.
2 changes: 1 addition & 1 deletion SysBot.Base/Connection/Console/IConsoleConnectionAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ public interface IConsoleConnectionAsync : IConsoleConnection
Task<byte[]> ReadBytesAsync(uint offset, int length, CancellationToken token);
Task WriteBytesAsync(byte[] data, uint offset, CancellationToken token);
Task<byte[]> PixelPeek(CancellationToken token);
Task<long> GetUnixTime(CancellationToken token);
Task<long> GetCurrentTime(CancellationToken token);
}
3 changes: 1 addition & 2 deletions SysBot.Base/Connection/Switch/ISwitchConnectionSync.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Security.Cryptography;
using System;
using System;

namespace SysBot.Base;

Expand Down
2 changes: 2 additions & 0 deletions SysBot.Base/Connection/Switch/SwitchConfigureParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@ public enum SwitchConfigureParameter
/// Amount of time (milliseconds) to sleep between Hid keypresses
/// </summary>
keySleepTime,

controllerType,
}
4 changes: 2 additions & 2 deletions SysBot.Base/Connection/Switch/USB/SwitchUSBAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,11 @@ public Task<byte[]> PixelPeek(CancellationToken token)
}, token);
}

public Task<long> GetUnixTime(CancellationToken token)
public Task<long> GetCurrentTime(CancellationToken token)
{
return Task.Run(() =>
{
Send(SwitchCommand.GetUnixTime(false));
Send(SwitchCommand.GetCurrentTime(false));
byte[] baseBytes = ReadBulkUSB();
return BitConverter.ToInt64(baseBytes, 0);
}, token);
Expand Down
10 changes: 5 additions & 5 deletions SysBot.Base/Connection/Switch/Wireless/SwitchSocketAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public async Task<string> GetBotbaseVersion(CancellationToken token)
public async Task<string> GetGameInfo(string info, CancellationToken token)
{
var bytes = await ReadRaw(SwitchCommand.GetGameInfo(info), 17, token).ConfigureAwait(false);
return Encoding.ASCII.GetString(bytes).Trim(['\0', '\n']);
return Encoding.ASCII.GetString(bytes).Trim('\0', '\n');
}

public async Task<bool> IsProgramRunning(ulong pid, CancellationToken token)
Expand Down Expand Up @@ -285,10 +285,10 @@ private async Task<byte[]> FlexRead(CancellationToken token)
return [.. flexBuffer];
}

public async Task<long> GetUnixTime(CancellationToken token)
public async Task<long> GetCurrentTime(CancellationToken token)
{
var result = await ReadBytesFromCmdAsync(SwitchCommand.GetUnixTime(), 8, token).ConfigureAwait(false);
Array.Reverse(result);
return BitConverter.ToInt64(result, 0);
var res = await ReadBytesFromCmdAsync(SwitchCommand.GetCurrentTime(), 8, token).ConfigureAwait(false);
Array.Reverse(res);
return BitConverter.ToInt64(res, 0);
}
}
2 changes: 1 addition & 1 deletion SysBot.Base/Connection/Switch/Wireless/SwitchSocketSync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private byte[] ReadResponse(int length)
Thread.Sleep((MaximumTransferSize / DelayFactor) + BaseDelay);
var size = (length * 2) + 1;
var buffer = ArrayPool<byte>.Shared.Rent(size);
var _ = Read(buffer, size);
_ = Read(buffer, size);
var mem = buffer.AsMemory(0, size);
var result = DecodeResult(mem, length);
ArrayPool<byte>.Shared.Return(buffer, true);
Expand Down
2 changes: 1 addition & 1 deletion SysBot.Base/Control/SwitchRoutineExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace SysBot.Base;
public abstract class SwitchRoutineExecutor<T> : RoutineExecutor<T> where T : class, IConsoleBotConfig
{
public readonly bool UseCRLF;
protected readonly ISwitchConnectionAsync SwitchConnection;
public readonly ISwitchConnectionAsync SwitchConnection;

protected SwitchRoutineExecutor(IConsoleBotManaged<IConsoleConnection, IConsoleConnectionAsync> Config) : base(Config)
{
Expand Down
4 changes: 2 additions & 2 deletions SysBot.Base/SysBot.Base.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.13.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="Discord.Net" Version="3.13.1" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="LibUsbDotNet" Version="2.2.29" />
</ItemGroup>

Expand Down
2 changes: 0 additions & 2 deletions SysBot.Base/Util/Logging/ILogForwarder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System;

namespace SysBot.Base;

/// <summary>
Expand Down
18 changes: 11 additions & 7 deletions SysBot.Base/Util/SwitchCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@ namespace SysBot.Base;
/// </summary>
public static class SwitchCommand
{
private static readonly Encoding Encoder = Encoding.ASCII;
public static readonly Encoding Encoder = Encoding.ASCII;

private static byte[] Encode(string command, bool crlf = true)
public static byte[] Encode(string command, bool crlf = true)
{
if (crlf)
command += "\r\n";
return Encoder.GetBytes(command);
}

private static string ToHex(byte[] data)
public static string ToHex(byte[] data)
=> string.Concat(data.Select(z => $"{z:X2}"));
private static string Encode(IEnumerable<long> jumps)
public static string Encode(IEnumerable<long> jumps)
=> string.Concat(jumps.Select(z => $" {z}"));
private static string Encode(IReadOnlyDictionary<ulong, int> offsetSizeDictionary)
public static string Encode(IReadOnlyDictionary<ulong, int> offsetSizeDictionary)
=> string.Concat(offsetSizeDictionary.Select(z => $" 0x{z.Key:X16} {z.Value}"));

private static string ToHex(ReadOnlySpan<byte> data)
public static string ToHex(ReadOnlySpan<byte> data)
{
var result = new StringBuilder(data.Length * 2);
foreach (var b in data)
Expand Down Expand Up @@ -342,7 +342,8 @@ public static byte[] SetScreen(ScreenState state, bool crlf = true)
public static byte[] IsProgramRunning(ulong pid, bool crlf = true)
=> Encode($"isProgramRunning 0x{pid:x16}", crlf);

public static byte[] GetUnixTime(bool crlf = true) => Encode("getUnixTime", crlf);
public static byte[] GetCurrentTime(bool crlf = true) => Encode("getCurrentTime", crlf);
public static byte[] SetCurrentTime(bool crlf = true) => Encode("setCurrentTime ", crlf);
public static byte[] TimeSkipBack(bool crlf = true) => Encode($"timeSkipBack", crlf);
public static byte[] TimeSkipForward(bool crlf = true) => Encode($"timeSkipForward", crlf);

Expand All @@ -363,6 +364,9 @@ public static byte[] DaySkip(bool crlf = true)
public static byte[] ResetTime(bool crlf = true)
=> Encode("resetTime", crlf);

public static byte[] ResetTimeNTP(bool crlf = true)
=> Encode("resetTimeNTP", crlf);

/// <summary>
/// Takes and sends a raw screenshot.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.ConsoleApp/SysBot.Pokemon.ConsoleApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.13.0" />
<PackageReference Include="Discord.Net" Version="3.13.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<ProjectReference Include="..\SysBot.Pokemon.Discord\SysBot.Pokemon.Discord.csproj" />
<ProjectReference Include="..\SysBot.Pokemon.Twitch\SysBot.Pokemon.Twitch.csproj" />
Expand Down
24 changes: 22 additions & 2 deletions SysBot.Pokemon.Discord/Commands/Bots/TradeModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ public async Task TradeAsync([Summary("Trade Code")] int code, [Summary("Showdow

if (pkm is not T pk || !la.Valid)
{
var reason = result == "Timeout" ? $"That {spec} set took too long to generate." : result == "VersionMismatch" ? "Request refused: PKHeX and Auto-Legality Mod version mismatch." : $"I wasn't able to create a {spec} from that set.";
var reason = result switch
{
"Timeout" => $"That {spec} set took too long to generate.",
"VersionMismatch" => "Request refused: PKHeX and Auto-Legality Mod version mismatch.",
_ => $"I wasn't able to create a {spec} from that set.",
};
var imsg = $"Oops! {reason}";
if (result == "Failed")
imsg += $"\n{AutoLegalityWrapper.GetLegalizationHint(template, sav, pkm)}";
Expand Down Expand Up @@ -120,7 +125,7 @@ public Task TradeAsyncAttach()
[RequireSudo]
public async Task BanTradeAsync([Summary("Online ID")] ulong nnid, string comment)
{
SysCordSettings.HubConfig.TradeAbuse.BannedIDs.AddIfNew(new[] { GetReference(nnid, comment) });
SysCordSettings.HubConfig.TradeAbuse.BannedIDs.AddIfNew([GetReference(nnid, comment)]);
await ReplyAsync("Done.").ConfigureAwait(false);
}

Expand Down Expand Up @@ -200,16 +205,31 @@ private async Task AddTradeToQueueAsync(int code, string trainerName, T pk, Requ
{
if (!pk.CanBeTraded())
{
// Disallow anything that cannot be traded from the game (e.g. Fusions).
await ReplyAsync("Provided Pokémon content is blocked from trading!").ConfigureAwait(false);
return;
}

var cfg = Info.Hub.Config.Trade;
var la = new LegalityAnalysis(pk);
if (!la.Valid)
{
// Disallow trading illegal Pokémon.
await ReplyAsync($"{typeof(T).Name} attachment is not legal, and cannot be traded!").ConfigureAwait(false);
return;
}
if (cfg.DisallowNonNatives && (la.EncounterOriginal.Context != pk.Context || pk.GO))
{
// Allow the owner to prevent trading entities that require a HOME Tracker even if the file has one already.
await ReplyAsync($"{typeof(T).Name} attachment is not native, and cannot be traded!").ConfigureAwait(false);
return;
}
if (cfg.DisallowTracked && pk is IHomeTrack { HasTracker: true })
{
// Allow the owner to prevent trading entities that already have a HOME Tracker.
await ReplyAsync($"{typeof(T).Name} attachment is tracked by HOME, and cannot be traded!").ConfigureAwait(false);
return;
}

await QueueHelper<T>.AddToQueueAsync(Context, code, trainerName, sig, pk, PokeRoutineType.LinkTrade, PokeTradeType.Specific, usr).ConfigureAwait(false);
}
Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.Discord/Commands/Extra/LegalizerModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public async Task LegalizeAsync()
[Command("convert"), Alias("showdown")]
[Summary("Tries to convert the Showdown Set to pkm data.")]
[Priority(1)]
public Task ConvertShowdown([Summary("Generation/Format")] int gen, [Remainder][Summary("Showdown Set")] string content)
public Task ConvertShowdown([Summary("Generation/Format")] byte gen, [Remainder][Summary("Showdown Set")] string content)
{
return Context.Channel.ReplyWithLegalizedSetAsync(content, gen);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public async Task ItemTrade([Remainder] string item)
public async Task ItemTrade([Summary("Trade Code")] int code, [Remainder] string item)
{
Species species = Info.Hub.Config.Trade.ItemTradeSpecies == Species.None ? Species.Diglett : Info.Hub.Config.Trade.ItemTradeSpecies;
var set = new ShowdownSet($"{SpeciesName.GetSpeciesNameGeneration((ushort)species, 2, 8)} @ {item.Trim()}");
var set = new ShowdownSet($"{SpeciesName.GetSpeciesNameGeneration((ushort)species, 2, 9)} @ {item.Trim()}");
var template = AutoLegalityWrapper.GetTemplate(set);
var sav = AutoLegalityWrapper.GetTrainerInfo<T>();
var pkm = sav.GetLegal(template, out var result);
Expand Down
16 changes: 7 additions & 9 deletions SysBot.Pokemon.Discord/Commands/Extra/TradeCordModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -546,8 +546,8 @@ public async Task TrainerInfoSet()
return;
}

var ot = pkm.OT_Name;
var gender = $"{(Gender)pkm.OT_Gender}";
var ot = pkm.OriginalTrainerName;
var gender = $"{(Gender)pkm.OriginalTrainerGender}";
var tid = $"{pkm.TID16}";
var sid = $"{pkm.SID16}";
var lang = $"{(LanguageID)pkm.Language}";
Expand Down Expand Up @@ -746,12 +746,13 @@ public async Task TradeCordBuddy([Remainder] string input = "")
var form = TradeExtensions<T>.FormOutput(result.Poke.Species, result.Poke.Form, out _).Replace("-", "");
var lvlProgress = (Experience.GetEXPToLevelUpPercentage(result.Poke.CurrentLevel, result.Poke.EXP, result.Poke.PersonalInfo.EXPGrowth) * 100.0).ToString("N1");
msg = $"\n**Nickname:** {result.User.Buddy.Nickname}" +
$"\n**Species:** {SpeciesName.GetSpeciesNameGeneration(result.Poke.Species, 2, 8)} {GameInfo.GenderSymbolUnicode[result.Poke.Gender].Replace("-", "")}" +
$"\n**Species:** {SpeciesName.GetSpeciesNameGeneration(result.Poke.Species, 2, 9)} {GameInfo.GenderSymbolUnicode[result.Poke.Gender].Replace("-", "")}" +
$"\n**Form:** {(form == string.Empty ? "-" : form)}" +
$"\n**Gigantamax:** {(canGmax ? "Yes" : "No")}" +
$"\n**Ability:** {result.User.Buddy.Ability}" +
$"\n**Level:** {result.Poke.CurrentLevel}" +
$"\n**Friendship:** {result.Poke.CurrentFriendship}" +
$"\n**Language:** {(LanguageID)result.Poke.Language}" +
$"\n**Held item:** {GameInfo.Strings.itemlist[result.Poke.HeldItem]}" +
$"\n**Time of day:** {TradeCordHelper<T>.TimeOfDayString(result.User.UserInfo.TimeZoneOffset, false)}" +
$"{(!result.Poke.IsEgg && result.Poke.CurrentLevel < 100 ? $"\n**Progress to next level:** {lvlProgress}%" : "")}";
Expand Down Expand Up @@ -803,10 +804,7 @@ public async Task TradeCordNickname([Remainder] string input)
[RequireQueueRole(nameof(DiscordManager.RolesTradeCord))]
public async Task TradeCordEvolution([Remainder][Summary("Usable item or Alcremie form.")] string input = "")
{
await ReplyAsync("To further bring the community together, evolutions has currently been turned off. ").ConfigureAwait(false);
return;

/*string name = $"{Context.User.Username}'s Evolution";
string name = $"{Context.User.Username}'s Evolution";
if (!TradeCordParanoiaChecks(out string msg))
{
await Util.EmbedUtil(Context, name, msg).ConfigureAwait(false);
Expand All @@ -815,7 +813,7 @@ public async Task TradeCordEvolution([Remainder][Summary("Usable item or Alcremi

input = input.Replace(" ", "").ToLower();
var ctx = new TradeCordHelper<T>.TC_CommandContext { Username = Context.User.Username, ID = Context.User.Id, Context = TCCommandContext.Evolution };
var result = await Helper.ProcessTradeCord(ctx, new string[] { input }).ConfigureAwait(false);
var result = await Helper.ProcessTradeCord(ctx, [input]).ConfigureAwait(false);
if (!result.Success)
{
await Util.EmbedUtil(Context, name, result.Message).ConfigureAwait(false);
Expand All @@ -835,7 +833,7 @@ public async Task TradeCordEvolution([Remainder][Summary("Usable item or Alcremi
Author = author,
}.WithFooter(x => { x.Text = flavorText; x.IconUrl = "https://i.imgur.com/nXNBrlr.png"; });

await Context.Channel.SendMessageAsync(null, false, embed: embed.Build()).ConfigureAwait(false);*/
await Context.Channel.SendMessageAsync(null, false, embed: embed.Build()).ConfigureAwait(false);
}

[Command("TradeCordGiveItem")]
Expand Down
4 changes: 1 addition & 3 deletions SysBot.Pokemon.Discord/Commands/General/InfoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class InfoModule : ModuleBase<SocketCommandContext>
{
private const string detail = "I am an open-source Discord bot powered by PKHeX.Core and other open-source software.";
private const string repo = "https://github.com/kwsch/SysBot.NET";
private const string fork = "https://github.com/Koi-3088/ForkBot.NET";
private const string notfork = "https://github.com/zyro670/NotForkBot.NET";

[Command("info")]
Expand All @@ -34,8 +33,7 @@ public async Task InfoAsync()

builder.AddField("Info",
$"- [Original Source Code]({repo})\n" +
$"- [This Fork's Source Code]({fork})\n" +
$"- [This Fork's Fork Source Code]({notfork})\n" +
$"- [This Fork's Source Code]({notfork})\n" +
$"- {Format.Bold("Owner")}: {app.Owner} ({app.Owner.Id})\n" +
$"- {Format.Bold("Library")}: Discord.Net ({DiscordConfig.Version})\n" +
$"- {Format.Bold("Uptime")}: {GetUptime()}\n" +
Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.Discord/Commands/Management/EchoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public async Task AddEchoAsync()
AddEchoChannel(c, cid);

// Add to discord global loggers (saves on program close)
SysCordSettings.Settings.EchoChannels.AddIfNew(new[] { GetReference(Context.Channel) });
SysCordSettings.Settings.EchoChannels.AddIfNew([GetReference(Context.Channel)]);
await ReplyAsync("Added Echo output to this channel!").ConfigureAwait(false);
}

Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.Discord/Commands/Management/LogModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task AddLogAsync()
AddLogChannel(c, cid);

// Add to discord global loggers (saves on program close)
SysCordSettings.Settings.LoggingChannels.AddIfNew(new[] { GetReference(Context.Channel) });
SysCordSettings.Settings.LoggingChannels.AddIfNew([GetReference(Context.Channel)]);
await ReplyAsync("Added logging output to this channel!").ConfigureAwait(false);
}

Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.Discord/Commands/Management/OwnerModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task RemoveSudoUsers([Remainder] string _)
public async Task AddChannel()
{
var obj = GetReference(Context.Message.Channel);
SysCordSettings.Settings.ChannelWhitelist.AddIfNew(new[] { obj });
SysCordSettings.Settings.ChannelWhitelist.AddIfNew([obj]);
await ReplyAsync("Done.").ConfigureAwait(false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public async Task AddLogAsync()
AddLogChannel(c, cid);

// Add to discord global loggers (saves on program close)
SysCordSettings.Settings.TradeStartingChannels.AddIfNew(new[] { GetReference(Context.Channel) });
SysCordSettings.Settings.TradeStartingChannels.AddIfNew([GetReference(Context.Channel)]);
await ReplyAsync("Added Start Notification output to this channel!").ConfigureAwait(false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel c
var spec = GameInfo.Strings.Species[template.Species];
if (!la.Valid)
{
var reason = result == "Timeout" ? $"That {spec} set took too long to generate." : result == "VersionMismatch" ? "Request refused: PKHeX and Auto-Legality Mod version mismatch." : $"I wasn't able to create a {spec} from that set.";
var reason = result switch
{
"Timeout" => $"That {spec} set took too long to generate.",
"VersionMismatch" => "Request refused: PKHeX and Auto-Legality Mod version mismatch.",
_ => $"I wasn't able to create a {spec} from that set.",
};
var imsg = $"Oops! {reason}";
if (result == "Failed")
imsg += $"\n{AutoLegalityWrapper.GetLegalizationHint(template, sav, pkm)}";
Expand All @@ -51,7 +56,7 @@ public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel c
}
}

public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, string content, int gen)
public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, string content, byte gen)
{
content = ReusableActions.StripCodeBlock(content);
var set = new ShowdownSet(content);
Expand Down
Loading

0 comments on commit efb99ae

Please sign in to comment.