- small bot.cs cleanup

- creds.yml now loads and reloads properly (from the current directory, like credentials.json)
- added empty creds.yml to repo, and added it to .gitignore
This commit is contained in:
Kwoth
2021-06-24 15:43:53 +02:00
parent 16dd398aa0
commit a1ef862382
13 changed files with 215 additions and 208 deletions

View File

@@ -10,7 +10,7 @@ namespace NadekoBot.Services
{
string Token { get; }
string GoogleApiKey { get; }
List<ulong> OwnerIds { get; }
ICollection<ulong> OwnerIds { get; }
string RapidApiKey { get; }
string PatreonAccessToken { get; }

View File

@@ -1,119 +1,63 @@
using Microsoft.Extensions.Configuration;
using System.IO;
using Microsoft.Extensions.Primitives;
using Nadeko.Common;
using NadekoBot.Common.Yml;
using Serilog;
namespace NadekoBot.Services
{
public static class BotCredentialsProvider
// todo check why is memory usage so unstable
public class BotCredsProvider
{
private const string _credsFileName = "creds.yml";
private static string _oldCredsJsonFilename = Path.Combine(Directory.GetCurrentDirectory(), "credentials.json");
private string CredsPath => Path.Combine(Directory.GetCurrentDirectory(), _credsFileName);
private const string _credsExampleFileName = "creds_example.yml";
private string CredsExamplePath => Path.Combine(Directory.GetCurrentDirectory(), _credsExampleFileName);
public static Creds CreateBotCredentials()
private string _oldCredsJsonFilename = Path.Combine(Directory.GetCurrentDirectory(), "credentials.json");
private Creds _creds = new Creds();
private IConfigurationRoot _config;
private readonly object reloadLock = new object();
private void Reload()
{
if (!File.Exists(_credsFileName))
Log.Warning($"{_credsFileName} is missing. " +
$"Attempting to load creds from environment variables prefixed with 'NadekoBot_'. " +
$"Example is in {Path.GetFullPath("./creds-example.yml")}");
IConfigurationBuilder configBuilder = new ConfigurationBuilder();
var creds = configBuilder
.AddYamlFile(_credsFileName, false, true)
.AddEnvironmentVariables("NadekoBot_")
.Build()
.Get<Creds>();
// if(string.IsNullOrWhiteSpace(creds.RedisOptions))
// creds.RedisOptions = ""
return creds;
// try
// {
//
//
// var data = configBuilder.Build();
//
// Token = data[nameof(Token)];
// if (string.IsNullOrWhiteSpace(Token))
// {
// Log.Error("Token is missing from credentials.json or Environment variables. Add it and restart the program.");
// Helpers.ReadErrorAndExit(5);
// }
//
// OwnerIds = data.GetSection("OwnerIds").GetChildren().Select(c => ulong.Parse(c.Value))
// .ToImmutableArray();
// GoogleApiKey = data[nameof(GoogleApiKey)];
// MashapeKey = data[nameof(MashapeKey)];
// OsuApiKey = data[nameof(OsuApiKey)];
// PatreonAccessToken = data[nameof(PatreonAccessToken)];
// PatreonCampaignId = data[nameof(PatreonCampaignId)] ?? "334038";
// ShardRunCommand = data[nameof(ShardRunCommand)];
// ShardRunArguments = data[nameof(ShardRunArguments)];
// CleverbotApiKey = data[nameof(CleverbotApiKey)];
// LocationIqApiKey = data[nameof(LocationIqApiKey)];
// TimezoneDbApiKey = data[nameof(TimezoneDbApiKey)];
// CoinmarketcapApiKey = data[nameof(CoinmarketcapApiKey)];
// if (string.IsNullOrWhiteSpace(CoinmarketcapApiKey))
// {
// CoinmarketcapApiKey = "e79ec505-0913-439d-ae07-069e296a6079";
// }
//
// if (!string.IsNullOrWhiteSpace(data[nameof(RedisOptions)]))
// RedisOptions = data[nameof(RedisOptions)];
// else
// RedisOptions = "127.0.0.1,syncTimeout=3000";
//
// VotesToken = data[nameof(VotesToken)];
// VotesUrl = data[nameof(VotesUrl)];
// BotListToken = data[nameof(BotListToken)];
//
// var restartSection = data.GetSection(nameof(RestartCommand));
// var cmd = restartSection["cmd"];
// var args = restartSection["args"];
// if (!string.IsNullOrWhiteSpace(cmd))
// RestartCommand = new RestartConfig(cmd, args);
//
// if (Environment.OSVersion.Platform == PlatformID.Unix)
// {
// if (string.IsNullOrWhiteSpace(ShardRunCommand))
// ShardRunCommand = "dotnet";
// if (string.IsNullOrWhiteSpace(ShardRunArguments))
// ShardRunArguments = "run -c Release --no-build -- {0} {1}";
// }
// else //windows
// {
// if (string.IsNullOrWhiteSpace(ShardRunCommand))
// ShardRunCommand = "NadekoBot.exe";
// if (string.IsNullOrWhiteSpace(ShardRunArguments))
// ShardRunArguments = "{0} {1}";
// }
//
// if (!int.TryParse(data[nameof(TotalShards)], out var ts))
// ts = 0;
// TotalShards = ts < 1 ? 1 : ts;
//
// CarbonKey = data[nameof(CarbonKey)];
// var dbSection = data.GetSection("db");
// Db = new DBConfig(@"sqlite",
// string.IsNullOrWhiteSpace(dbSection["ConnectionString"])
// ? "Data Source=data/NadekoBot.db"
// : dbSection["ConnectionString"]);
//
// TwitchClientId = data[nameof(TwitchClientId)];
// if (string.IsNullOrWhiteSpace(TwitchClientId))
// {
// TwitchClientId = "67w6z9i09xv2uoojdm9l0wsyph4hxo6";
// }
// }
// catch (Exception ex)
// {
// Log.Error("JSON serialization has failed. Fix your credentials file and restart the bot.");
// Log.Fatal(ex.ToString());
// Helpers.ReadErrorAndExit(6);
// }
lock (reloadLock)
{
_creds.OwnerIds.Clear();
_config.Bind(_creds);
// todo load defaults for restart command, redis, and some others maybe?
}
}
public BotCredsProvider()
{
if (!File.Exists(CredsExamplePath))
{
File.WriteAllText(CredsExamplePath, Yaml.Serializer.Serialize(_creds));
}
if (!File.Exists(CredsPath))
{
Log.Warning($"{CredsPath} is missing. " +
$"Attempting to load creds from environment variables prefixed with 'NadekoBot_'. " +
$"Example is in {CredsExamplePath}");
}
_config = new ConfigurationBuilder()
.AddYamlFile(CredsPath, false, true)
.AddEnvironmentVariables("NadekoBot_")
.Build();
ChangeToken.OnChange(
() => _config.GetReloadToken(),
Reload);
Reload();
}
public Creds GetCreds() => _creds;
}
}

View File

@@ -5,6 +5,8 @@ using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace NadekoBot.Services
{
@@ -18,14 +20,12 @@ namespace NadekoBot.Services
private readonly string _redisKey;
private readonly EndPoint _redisEndpoint;
public RedisCache(IBotCredentials creds, int shardId)
public RedisCache(ConnectionMultiplexer redis, IBotCredentials creds, DiscordSocketClient client)
{
var conf = ConfigurationOptions.Parse(creds.RedisOptions);
Redis = ConnectionMultiplexer.Connect(conf);
Redis = redis;
_redisEndpoint = Redis.GetEndPoints().First();
LocalImages = new RedisImagesCache(Redis, creds);
LocalData = new RedisLocalDataCache(Redis, creds, shardId);
LocalData = new RedisLocalDataCache(Redis, creds, client.ShardId);
_redisKey = creds.RedisKey();
}