Skip to content

Commit

Permalink
Merge pull request #276 from Unity-Developer-Community/feat/even-more…
Browse files Browse the repository at this point in the history
…-misc

Couple Fixes
  • Loading branch information
Pierre-Demessence authored Mar 20, 2024
2 parents 0e1bc09 + 881c1cf commit 943d7db
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 14 deletions.
6 changes: 4 additions & 2 deletions DiscordBot/Extensions/UserDBRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ public static class UserProps

public interface IServerUserRepo
{
[Sql($"INSERT INTO {UserProps.TableName} ({UserProps.UserID}) VALUES (@{UserProps.UserID})")]
Task InsertUser(ServerUser user);
[Sql($@"
INSERT INTO {UserProps.TableName} ({UserProps.UserID}) VALUES (@{UserProps.UserID});
SELECT * FROM {UserProps.TableName} WHERE {UserProps.UserID} = @{UserProps.UserID}")]
Task<ServerUser> InsertUser(ServerUser user);
[Sql($"DELETE FROM {UserProps.TableName} WHERE {UserProps.UserID} = @userId")]
Task RemoveUser(string userId);

Expand Down
6 changes: 6 additions & 0 deletions DiscordBot/Modules/UserModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,12 @@ public async Task RollDice(int sides, int number)
[Summary("Roll a D20 dice.")]
public async Task RollD20(int number)
{
if (number < 1)
{
await ReplyAsync("Invalid number. Please choose a number 1 or above.").DeleteAfterSeconds(seconds: 10);
await Context.Message.DeleteAsync();
return;
}
var roll = _random.Next(1, 21);
var message = $"**{Context.User.Username}** rolled a D20 and got **{roll}**!";
if (roll > number)
Expand Down
10 changes: 6 additions & 4 deletions DiscordBot/Services/CurrencyService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class CurrencyService
#region Configuration

private const int ApiVersion = 1;
private const string TargetDate = "latest";
private const string ValidCurrenciesEndpoint = "currencies.min.json";
private const string ExchangeRatesEndpoint = "currencies";

Expand All @@ -23,24 +24,25 @@ private class Currency

private readonly Dictionary<string, Currency> _currencies = new();

private static readonly string ApiUrl = $"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@{ApiVersion}/latest/";
private static readonly string ApiUrl = $"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{TargetDate}/v{ApiVersion}/";

public async Task<float> GetConversion(string toCurrency, string fromCurrency = "usd")
{
toCurrency = toCurrency.ToLower();
fromCurrency = fromCurrency.ToLower();

var url = $"{ApiUrl}{ExchangeRatesEndpoint}/{fromCurrency.ToLower()}/{toCurrency.ToLower()}.min.json";
var url = $"{ApiUrl}{ExchangeRatesEndpoint}/{fromCurrency.ToLower()}.min.json";

// Check if success
var (success, response) = await WebUtil.TryGetObjectFromJson<JObject>(url);
if (!success)
return -1;

// Check currency exists in response
response.TryGetValue($"{toCurrency}", out var value);
// json[fromCurrency][toCurrency]
var value = response.SelectToken($"{fromCurrency}.{toCurrency}");
if (value == null)
return -1;

return value.Value<float>();
}

Expand Down
26 changes: 23 additions & 3 deletions DiscordBot/Services/DatabaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class DatabaseService

private readonly ILoggingService _logging;
private string ConnectionString { get; }

public IServerUserRepo Query { get; }

public DatabaseService(ILoggingService logging, BotSettings settings)
Expand Down Expand Up @@ -159,6 +159,20 @@ await _logging.LogChannelAndFile(
/// <returns>Existing or newly created user. Null on database error.</returns>
public async Task<ServerUser> GetOrAddUser(SocketGuildUser socketUser)
{
if (socketUser == null)
{
await _logging.Log(LogBehaviour.ConsoleChannelAndFile,
$"SocketUser is null", ExtendedLogSeverity.Warning);
return null;
}

if (Query == null)
{
await _logging.Log(LogBehaviour.ConsoleChannelAndFile,
$"Query is null", ExtendedLogSeverity.Warning);
return null;
}

try
{
var user = await Query.GetUser(socketUser.Id.ToString());
Expand All @@ -170,8 +184,14 @@ public async Task<ServerUser> GetOrAddUser(SocketGuildUser socketUser)
UserID = socketUser.Id.ToString(),
};

await Query.InsertUser(user);
user = await Query.GetUser(socketUser.Id.ToString());
user = await Query.InsertUser(user);

if (user == null)
{
await _logging.Log(LogBehaviour.ConsoleChannelAndFile,
$"User is null after InsertUser", ExtendedLogSeverity.Warning);
return null;
}

await _logging.Log(LogBehaviour.File,
$"User {socketUser.GetPreferredAndUsername()} successfully added to the database.");
Expand Down
6 changes: 3 additions & 3 deletions DiscordBot/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,13 @@ public async Task UpdateXp(SocketMessage messageParam)
return;

var userId = messageParam.Author.Id;
if (_xpCooldown.HasUser(userId))
return;

var waitTime = _rand.Next(_xpMinCooldown, _xpMaxCooldown);
float baseXp = _rand.Next(_xpMinPerMessage, _xpMaxPerMessage);
float bonusXp = 0;

if (_xpCooldown.HasUser(userId))
return;

// Add Delay and delay action by 200ms to avoid some weird database collision?
_xpCooldown.AddCooldown(userId, waitTime);
Task.Run(async () =>

Check warning on line 227 in DiscordBot/Services/UserService.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Check warning on line 227 in DiscordBot/Services/UserService.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
Expand Down
4 changes: 2 additions & 2 deletions DiscordBot/Settings/Deserialized/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public class BotSettings

#region Fun Commands

public List<string> UserModuleSlapChoices { get; set; } = new List<string>() { "trout", "duck", "truck", "paddle", "magikarp", "sausage", "student loan", "low poly donut" };

public List<string> UserModuleSlapChoices { get; set; } = new List<string>() { "trout", "duck", "truck", "paddle", "magikarp", "sausage", "student loan", "life choice", "bug report", "unhandled exception", "null pointer", "keyboard", "cheese wheel", "banana peel", "unresolved bug", "low poly donut" };
#endregion // Fun Commands

#region Service Enabling
Expand Down

0 comments on commit 943d7db

Please sign in to comment.