Skip to content

Commit

Permalink
Version bump => 2.8.7
Browse files Browse the repository at this point in the history
- Include Native check for AutoOT
- Clean up code
- Add Stellar Tera Type to Emoji Settings
  • Loading branch information
bdawg1989 committed Jun 12, 2024
1 parent 20801a1 commit 8ac6610
Show file tree
Hide file tree
Showing 36 changed files with 216 additions and 206 deletions.
3 changes: 1 addition & 2 deletions SysBot.Base/Connection/Switch/Wireless/SwitchSocketAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ public async Task<byte[]> PixelPeek(CancellationToken token)

try
{
var result = Decoder.ConvertHexByteStringToBytes(data);
return result;
return Decoder.ConvertHexByteStringToBytes(data);
}
catch (Exception e)
{
Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Bilibili/BilibiliLiveBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,7 @@ private static int GenerateUniqueTradeID()
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
int randomValue = new Random().Next(1000);
int uniqueTradeID = ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
return uniqueTradeID;
return ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
}
}
}
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Discord/Commands/Bots/Pokepaste.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,7 @@ private static List<ShowdownSet> ParseShowdownSets(string pokePasteHtml)
{
var showdownSets = new List<ShowdownSet>();
var regex = new Regex(@"<pre>(.*?)</pre>", RegexOptions.Singleline);
var matches = regex.Matches(pokePasteHtml);
foreach (Match match in matches)
foreach (Match match in regex.Matches(pokePasteHtml))
{
var showdownText = match.Groups[1].Value;
showdownText = System.Net.WebUtility.HtmlDecode(Regex.Replace(showdownText, "<.*?>", string.Empty));
Expand Down
6 changes: 2 additions & 4 deletions SysBot.Pokemon.Discord/Commands/Bots/SpecialRequestModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,7 @@ private static EmbedBuilder BuildEventListEmbed(string generationOrGame, IOrdere
.WithDescription($"Page {page} of {pageCount}")
.WithColor(DiscordColor.Blue);

var pageItems = allEvents.Skip((page - 1) * itemsPerPage).Take(itemsPerPage);
foreach (var item in pageItems)
foreach (var item in allEvents.Skip((page - 1) * itemsPerPage).Take(itemsPerPage))
{
embed.AddField($"{item.Index}. {item.EventInfo}", $"Use `{botPrefix}srp {generationOrGame} {item.Index}` to request this event.");
}
Expand Down Expand Up @@ -269,8 +268,7 @@ private async Task CleanupUserMessageAsync()
var (start, end) = GetEncounterDateRange(selectedEvent);
if (start.HasValue && end.HasValue)
{
var randomDate = GenerateRandomDateInRange(start.Value, end.Value);
pk.MetDate = randomDate;
pk.MetDate = GenerateRandomDateInRange(start.Value, end.Value);
}
else
{
Expand Down
5 changes: 2 additions & 3 deletions SysBot.Pokemon.Discord/Commands/Bots/TradeModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -732,10 +732,9 @@ public async Task BatchTradeAsync([Summary("List of Showdown Sets separated by '
private static List<string> ParseBatchTradeContent(string content)
{
var delimiters = new[] { "---", "—-" }; // Includes both three hyphens and an em dash followed by a hyphen
var trades = content.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
return content.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
.Select(trade => trade.Trim())
.ToList();
return trades;
}

[Command("batchtradezip")]
Expand Down Expand Up @@ -777,7 +776,7 @@ public async Task BatchTradeZipAsync()
using var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
var entries = archive.Entries.ToList();

var maxTradesAllowed = 6; // for full team in the zip created
const int maxTradesAllowed = 6; // for full team in the zip created

// Check if batch mode is allowed and if the number of trades exceeds the limit
if (maxTradesAllowed < 1 || entries.Count > maxTradesAllowed)
Expand Down
12 changes: 4 additions & 8 deletions SysBot.Pokemon.Discord/Commands/Bots/VGCPastes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,14 @@ private static async Task<string> DownloadSpreadsheetAsCsv()
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync(csvUrl);
response.EnsureSuccessStatusCode();
var csvData = await response.Content.ReadAsStringAsync();
return csvData;
return await response.Content.ReadAsStringAsync();
}

private async Task<List<List<string>>> FetchSpreadsheetData()
{
var csvData = await VGCPastes<T>.DownloadSpreadsheetAsCsv();
var rows = csvData.Split('\n');
var data = rows.Select(row => row.Split(',').Select(cell => cell.Trim('"')).ToList()).ToList();
return data;
return rows.Select(row => row.Split(',').Select(cell => cell.Trim('"')).ToList()).ToList();
}

private static List<(string TrainerName, string PokePasteUrl, string TeamDescription, string DateShared, string RentalCode)> ParsePokePasteData(List<List<string>> data, string? pokemonName = null)
Expand Down Expand Up @@ -260,8 +258,7 @@ private static async Task<List<ShowdownSet>> GetShowdownSetsFromPokePasteUrl(str
{
var httpClient = new HttpClient();
var pokePasteHtml = await httpClient.GetStringAsync(pokePasteUrl);
var showdownSets = ParseShowdownSets(pokePasteHtml);
return showdownSets;
return ParseShowdownSets(pokePasteHtml);
}

private static List<ShowdownSet> ParseShowdownSets(string pokePasteHtml)
Expand Down Expand Up @@ -317,8 +314,7 @@ private static System.Drawing.Image CombineImages(List<System.Drawing.Image> ima
private static string SanitizeFileName(string fileName)
{
var invalidChars = Path.GetInvalidFileNameChars();
var validName = string.Join("_", fileName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
return validName;
return string.Join("_", fileName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
}

private static DiscordColor GetTypeColor()
Expand Down
6 changes: 2 additions & 4 deletions SysBot.Pokemon.Discord/Commands/Extra/LegalityCheckModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@ public class LegalityCheckModule : ModuleBase<SocketCommandContext>
[Summary("Verifies the attachment for legality.")]
public async Task LegalityCheck()
{
var attachments = Context.Message.Attachments;
foreach (var att in attachments)
foreach (var att in (System.Collections.Generic.IReadOnlyCollection<Attachment>)Context.Message.Attachments)
await LegalityCheck(att, false).ConfigureAwait(false);
}

[Command("lcv"), Alias("verbose")]
[Summary("Verifies the attachment for legality with a verbose output.")]
public async Task LegalityCheckVerbose()
{
var attachments = Context.Message.Attachments;
foreach (var att in attachments)
foreach (var att in (System.Collections.Generic.IReadOnlyCollection<Attachment>)Context.Message.Attachments)
await LegalityCheck(att, true).ConfigureAwait(false);
}

Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Discord/Commands/Extra/LegalizerModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public Task ConvertShowdown([Remainder][Summary("Showdown Set")] string content)
[Summary("Tries to legalize the attached pkm data.")]
public async Task LegalizeAsync()
{
var attachments = Context.Message.Attachments;
foreach (var att in attachments)
foreach (var att in (System.Collections.Generic.IReadOnlyCollection<global::Discord.Attachment>)Context.Message.Attachments)
await Context.Channel.ReplyWithLegalizedSetAsync(att).ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ namespace SysBot.Pokemon.Discord;
[RequireSudo]
public async Task TossAsync(string name = "")
{
var bots = SysCord<T>.Runner.Bots.Select(z => z.Bot);
foreach (var b in bots)
foreach (var b in SysCord<T>.Runner.Bots.Select(z => z.Bot))
{
if (b is not IEncounterBot x)
continue;
Expand Down
6 changes: 3 additions & 3 deletions SysBot.Pokemon.Discord/Commands/Management/OwnerModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ public async Task RePeek()
}

await using MemoryStream ms = new(bytes);
var img = "cap.jpg";
const string img = "cap.jpg";
var embed = new EmbedBuilder { ImageUrl = $"attachment://{img}", Color = (DiscordColor?)Color.Purple }
.WithFooter(new EmbedFooterBuilder { Text = "Here's your screenshot." });

Expand Down Expand Up @@ -295,7 +295,7 @@ public async Task RePeekGIF()
return;
}

var screenshotCount = 10;
const int screenshotCount = 10;
var screenshotInterval = TimeSpan.FromSeconds(0.1 / 10);
#pragma warning disable CA1416 // Validate platform compatibility
var gifFrames = new List<System.Drawing.Image>();
Expand Down Expand Up @@ -350,7 +350,7 @@ public async Task RePeekGIF()
}

ms.Position = 0;
var gifFileName = "screenshot.gif";
const string gifFileName = "screenshot.gif";
var embed = new EmbedBuilder { ImageUrl = $"attachment://{gifFileName}", Color = (DiscordColor?)Color.Red }
.WithFooter(new EmbedFooterBuilder { Text = "Here's your GIF." });

Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Discord/Commands/Management/SudoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ public async Task BlackListUsers(ulong id, [Remainder] string comment)
[RequireSudo]
public async Task ForgetPreviousUser([Summary("Comma Separated Online IDs")][Remainder] string content)
{
var IDs = GetIDs(content);
foreach (var ID in IDs)
foreach (var ID in GetIDs(content))
{
PokeRoutineExecutorBase.PreviousUsers.RemoveAllNID(ID);
PokeRoutineExecutorBase.PreviousUsersDistribution.RemoveAllNID(ID);
Expand Down
28 changes: 8 additions & 20 deletions SysBot.Pokemon.Discord/Helpers/DetailsExtractor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static SysBot.Pokemon.TradeSettings;

namespace SysBot.Pokemon.Discord;

public class DetailsExtractor<T> where T : PKM, new()
public static class DetailsExtractor<T> where T : PKM, new()
{
public static void AddAdditionalText(EmbedBuilder embedBuilder)
{
Expand Down Expand Up @@ -104,15 +105,14 @@ public static EmbedData ExtractPokemonDetails(T pk, SocketUser user, bool isMyst
embedData.IVsDisplay = ivsDisplay;

int[] evs = GetEVs(pk);
string evsDisplay = string.Join(" / ", new[] {
embedData.EVsDisplay = string.Join(" / ", new[] {
(evs[0] != 0 ? $"{evs[0]} HP" : ""),
(evs[1] != 0 ? $"{evs[1]} Atk" : ""),
(evs[2] != 0 ? $"{evs[2]} Def" : ""),
(evs[4] != 0 ? $"{evs[4]} SpA" : ""),
(evs[5] != 0 ? $"{evs[5]} SpD" : ""),
(evs[3] != 0 ? $"{evs[3]} Spe" : "") // correct pkhex/ALM ordering of stats
}.Where(s => !string.IsNullOrEmpty(s)));
embedData.EVsDisplay = evsDisplay;
embedData.MetDate = pk.MetDate.ToString();
embedData.MovesDisplay = string.Join("\n", embedData.Moves);
embedData.PokemonDisplayName = pk.IsNicknamed ? pk.Nickname : embedData.SpeciesName;
Expand Down Expand Up @@ -180,14 +180,14 @@ private static List<string> GetMoveNames(T pk)

var typeEmojis = SysCord<T>.Runner.Config.Trade.TradeEmbedSettings.CustomTypeEmojis
.Where(e => !string.IsNullOrEmpty(e.EmojiCode))
.ToDictionary(e => e.MoveType, e => $"{e.EmojiCode}");
.ToDictionary(e => (PKHeX.Core.MoveType)e.MoveType, e => $"{e.EmojiCode}");

for (int i = 0; i < moves.Length; i++)
{
if (moves[i] == 0) continue;
string moveName = GameInfo.MoveDataSource.FirstOrDefault(m => m.Value == moves[i])?.Text ?? "";
byte moveTypeId = MoveInfo.GetType(moves[i], default);
MoveType moveType = (MoveType)moveTypeId;
PKHeX.Core.MoveType moveType = (PKHeX.Core.MoveType)moveTypeId;
string formattedMove = $"{moveName} ({movePPs[i]}pp)";
if (SysCord<T>.Runner.Config.Trade.TradeEmbedSettings.MoveTypeEmojis && typeEmojis.TryGetValue(moveType, out var moveEmoji))
{
Expand Down Expand Up @@ -245,26 +245,14 @@ private static string GetTeraTypeString(PK9 pk9)
{
if (SysCord<T>.Runner.Config.Trade.TradeEmbedSettings.UseTeraEmojis)
{
var teraType = pk9.TeraTypeOverride == (MoveType)TeraTypeUtil.Stellar ? MoveType.Normal : pk9.TeraType;
var emojiInfo = SysCord<T>.Runner.Config.Trade.TradeEmbedSettings.TeraTypeEmojis.FirstOrDefault(e => e.MoveType == teraType);
var teraType = pk9.TeraTypeOverride == (PKHeX.Core.MoveType)TeraTypeUtil.Stellar || (int)pk9.TeraType == 99 ? TradeSettings.MoveType.Stellar : (TradeSettings.MoveType)pk9.TeraType;
var emojiInfo = SysCord<T>.Runner.Config.Trade.TradeEmbedSettings.TeraTypeEmojis.Find(e => e.MoveType == teraType);
if (emojiInfo != null && !string.IsNullOrEmpty(emojiInfo.EmojiCode))
{
return emojiInfo.EmojiCode;
}
}

if (pk9.TeraTypeOverride == (MoveType)TeraTypeUtil.Stellar)
{
return "Stellar";
}
else if ((int)pk9.TeraType == 99) // Terapagos
{
return "Stellar";
}
else
{
return pk9.TeraType.ToString();
}
return pk9.TeraType.ToString();
}

private static string GetTradeTitle(bool isMysteryEgg, bool isCloneRequest, bool isDumpRequest, bool isFixOTRequest, bool isSpecialRequest, bool isBatchTrade, int batchTradeNumber, string pokemonDisplayName, bool isShiny)
Expand Down
5 changes: 1 addition & 4 deletions SysBot.Pokemon.Discord/Helpers/DiscordTradeNotifier.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
using Discord;
using Discord.WebSocket;
using PKHeX.Core;
using PKHeX.Core.AutoMod;
using PKHeX.Drawing.PokeSprite;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Color = Discord.Color;

Expand Down Expand Up @@ -48,7 +45,7 @@ public DiscordTradeNotifier(T data, PokeTradeTrainerInfo info, int code, SocketU

public void TradeInitialize(PokeRoutineExecutor<T> routine, PokeTradeDetail<T> info)
{
int language = 2;
const int language = 2;
var speciesName = SpeciesName.GetSpeciesName(Data.Species, language);
var batchInfo = TotalBatchTrades > 1 ? $" (Trade {BatchTradeNumber} of {TotalBatchTrades})" : "";
var receive = Data.Species == 0 ? string.Empty : $" ({Data.Nickname})";
Expand Down
5 changes: 2 additions & 3 deletions SysBot.Pokemon.Discord/Helpers/QueueHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,7 @@ private static int GenerateUniqueTradeID()
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
int randomValue = new Random().Next(1000);
int uniqueTradeID = ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
return uniqueTradeID;
return ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
}

private static string GetImageFolderPath()
Expand Down Expand Up @@ -253,7 +252,7 @@ private static string SaveImageLocally(System.Drawing.Image image)

if (pk.IsEgg)
{
string eggImageUrl = "https://raw.githubusercontent.com/bdawg1989/sprites/main/egg.png";
const string eggImageUrl = "https://raw.githubusercontent.com/bdawg1989/sprites/main/egg.png";
speciesImageUrl = AbstractTrade<T>.PokeImg(pk, false, true, null);
System.Drawing.Image combinedImage = await OverlaySpeciesOnEgg(eggImageUrl, speciesImageUrl);
embedImageUrl = SaveImageLocally(combinedImage);
Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Discord/SysCord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,7 @@ public async Task InitCommands()
var assembly = Assembly.GetExecutingAssembly();

await _commands.AddModulesAsync(assembly, _services).ConfigureAwait(false);
var genericTypes = assembly.DefinedTypes.Where(z => z.IsSubclassOf(typeof(ModuleBase<SocketCommandContext>)) && z.IsGenericType);
foreach (var t in genericTypes)
foreach (var t in assembly.DefinedTypes.Where(z => z.IsSubclassOf(typeof(ModuleBase<SocketCommandContext>)) && z.IsGenericType))
{
var genModule = t.MakeGenericType(typeof(T));
await _commands.AddModuleAsync(genModule, _services).ConfigureAwait(false);
Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Twitch/TwitchBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ private static int GenerateUniqueTradeID()
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
int randomValue = new Random().Next(1000);
int uniqueTradeID = ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
return uniqueTradeID;
return ((int)(timestamp % int.MaxValue) * 1000) + randomValue;
}

private bool AddToTradeQueue(T pk, int code, OnWhisperReceivedArgs e, RequestSignificance sig, PokeRoutineType type, out string msg)
Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.WinForms/Controls/BotController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ public void ReloadStatus(BotSource<PokeBotState> b)
{
// blend from green->red, favoring green until near saturation
var factor = seconds / (double)threshold;
var blend = Blend(bad, good, factor * factor);
PB_Lamp.BackColor = blend;
PB_Lamp.BackColor = Blend(bad, good, factor * factor);
}
}

Expand Down
2 changes: 1 addition & 1 deletion SysBot.Pokemon.WinForms/UpdateChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static async Task<string> FetchChangelogAsync()

#pragma warning disable CS8604 // Possible null reference argument.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
string? downloadUrl = latestRelease.Assets.FirstOrDefault(a => a.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))?.BrowserDownloadUrl;
string? downloadUrl = latestRelease.Assets.Find(a => a.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))?.BrowserDownloadUrl;
#pragma warning restore CS8602 // Dereference of a possibly null reference.
#pragma warning restore CS8604 // Possible null reference argument.

Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.WinForms/UpdateForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ private void InitializeComponent()
private async Task FetchAndDisplayChangelog()
{
_ = new UpdateChecker();
string changelog = await UpdateChecker.FetchChangelogAsync();
textBoxChangelog.Text = changelog;
textBoxChangelog.Text = await UpdateChecker.FetchChangelogAsync();
}

private async void ButtonDownload_Click(object? sender, EventArgs? e)
Expand Down
6 changes: 2 additions & 4 deletions SysBot.Pokemon.Z3/Z3/Z3Search.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,14 @@ public static class Z3Search
{
public static IEnumerable<ulong> FindPotentialSeeds(uint ec, uint pid)
{
var seeds = new XoroMachineSkip(ec, pid);
foreach (var seed in seeds)
foreach (var seed in new XoroMachineSkip(ec, pid))
yield return seed;
}

public static IList<SeedSearchResult> GetAllSeeds(uint ec, uint pid, Span<int> ivs, SeedCheckResults mode)
{
var result = new List<SeedSearchResult>();
var seeds = GetSeeds(ec, pid);
foreach (var seed in seeds)
foreach (var seed in GetSeeds(ec, pid))
{
// Verify the IVs; at most 5 can match
bool added = false;
Expand Down
3 changes: 1 addition & 2 deletions SysBot.Pokemon.Z3/Z3/Z3SeedSearchHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ public void CalculateAndNotify(T pkm, PokeTradeDetail<T> detail, SeedCheckSettin

if (settings.ShowAllZ3Results)
{
var matches = Z3Search.GetAllSeeds(ec, pid, IVs, settings.ResultDisplayMode);
foreach (var match in matches)
foreach (var match in Z3Search.GetAllSeeds(ec, pid, IVs, settings.ResultDisplayMode))
{
var lump = new PokeTradeSummary("Calculated Seed:", match);
detail.SendNotification(bot, lump);
Expand Down
Loading

0 comments on commit 8ac6610

Please sign in to comment.