ready to use new client

This commit is contained in:
Kwoth 2017-01-15 02:08:14 +01:00
parent 88eabf6d90
commit 3926bc707b
14 changed files with 64 additions and 51 deletions

View File

@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Administration
{ {
private const string clockEmojiUrl = "https://cdn.discordapp.com/attachments/155726317222887425/258309524966866945/clock.png"; private const string clockEmojiUrl = "https://cdn.discordapp.com/attachments/155726317222887425/258309524966866945/clock.png";
private static ShardedDiscordClient _client { get; } private static DiscordShardedClient _client { get; }
private static Logger _log { get; } private static Logger _log { get; }
private static string prettyCurrentTime => $"【{DateTime.Now:HH:mm:ss}】"; private static string prettyCurrentTime => $"【{DateTime.Now:HH:mm:ss}】";
@ -81,7 +81,7 @@ namespace NadekoBot.Modules.Administration
_client.UserPresenceUpdated += _client_UserPresenceUpdated; _client.UserPresenceUpdated += _client_UserPresenceUpdated;
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated; _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated;
_client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS; _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated_TTS;
_client.GuildUserUpdated += _client_GuildUserUpdated; _client.GuildMemberUpdated += _client_GuildUserUpdated;
#if !GLOBAL_NADEKO #if !GLOBAL_NADEKO
_client.UserUpdated += _client_UserUpdated; _client.UserUpdated += _client_UserUpdated;
#endif #endif

View File

@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(status)) if (string.IsNullOrWhiteSpace(status))
continue; continue;
PlayingPlaceholders.ForEach(e => status = status.Replace(e.Key, e.Value())); PlayingPlaceholders.ForEach(e => status = status.Replace(e.Key, e.Value()));
await NadekoBot.Client.SetGame(status); await NadekoBot.Client.SetGameAsync(status).ConfigureAwait(false);
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendErrorAsync("⚠️ Cannot find that server").ConfigureAwait(false); await Context.Channel.SendErrorAsync("⚠️ Cannot find that server").ConfigureAwait(false);
return; return;
} }
if (server.OwnerId != NadekoBot.Client.CurrentUser().Id) if (server.OwnerId != NadekoBot.Client.CurrentUser.Id)
{ {
await server.LeaveAsync().ConfigureAwait(false); await server.LeaveAsync().ConfigureAwait(false);
await Context.Channel.SendConfirmAsync("✅ Left server " + server.Name).ConfigureAwait(false); await Context.Channel.SendConfirmAsync("✅ Left server " + server.Name).ConfigureAwait(false);
@ -57,7 +57,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(newName)) if (string.IsNullOrWhiteSpace(newName))
return; return;
await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Username = newName).ConfigureAwait(false); await NadekoBot.Client.CurrentUser.ModifyAsync(u => u.Username = newName).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync($"Bot name changed to **{newName}**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Bot name changed to **{newName}**").ConfigureAwait(false);
} }
@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Administration
[OwnerOnly] [OwnerOnly]
public async Task SetStatus([Remainder] SettableUserStatus status) public async Task SetStatus([Remainder] SettableUserStatus status)
{ {
await NadekoBot.Client.SetStatus(status); await NadekoBot.Client.SetStatusAsync(SettableUserStatusToUserStatus(status)).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync($"Bot status changed to **{status}**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Bot status changed to **{status}**").ConfigureAwait(false);
} }
@ -86,7 +86,7 @@ namespace NadekoBot.Modules.Administration
await sr.CopyToAsync(imgStream); await sr.CopyToAsync(imgStream);
imgStream.Position = 0; imgStream.Position = 0;
await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); await NadekoBot.Client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false);
} }
} }
@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Administration
[OwnerOnly] [OwnerOnly]
public async Task SetGame([Remainder] string game = null) public async Task SetGame([Remainder] string game = null)
{ {
await NadekoBot.Client.SetGame(game).ConfigureAwait(false); await NadekoBot.Client.SetGameAsync(game).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync("👾 **New game set.**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("👾 **New game set.**").ConfigureAwait(false);
} }
@ -108,7 +108,7 @@ namespace NadekoBot.Modules.Administration
{ {
name = name ?? ""; name = name ?? "";
await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); await NadekoBot.Client.SetGameAsync(name, url, StreamType.Twitch).ConfigureAwait(false);
await Context.Channel.SendConfirmAsync(" **New stream set.**").ConfigureAwait(false); await Context.Channel.SendConfirmAsync(" **New stream set.**").ConfigureAwait(false);
} }
@ -169,6 +169,23 @@ namespace NadekoBot.Modules.Administration
await Context.Channel.SendConfirmAsync("🆗").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("🆗").ConfigureAwait(false);
} }
private static UserStatus SettableUserStatusToUserStatus(SettableUserStatus sus)
{
switch (sus)
{
case SettableUserStatus.Online:
return UserStatus.Online;
case SettableUserStatus.Invisible:
return UserStatus.Invisible;
case SettableUserStatus.Idle:
return UserStatus.AFK;
case SettableUserStatus.Dnd:
return UserStatus.DoNotDisturb;
}
return UserStatus.Online;
}
} }
} }
} }

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.CustomReactions
public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>() public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>()
{ {
{"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser().Id}>"; } }, {"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser.Id}>"; } },
{"%user%", (ctx) => { return ctx.Author.Mention; } }, {"%user%", (ctx) => { return ctx.Author.Mention; } },
{"%rnduser%", (ctx) => { {"%rnduser%", (ctx) => {
var ch = ctx.Channel as ITextChannel; var ch = ctx.Channel as ITextChannel;

View File

@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Games
if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot)) if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot))
return false; return false;
var nadekoId = NadekoBot.Client.CurrentUser().Id; var nadekoId = NadekoBot.Client.CurrentUser.Id;
var normalMention = $"<@{nadekoId}> "; var normalMention = $"<@{nadekoId}> ";
var nickMention = $"<@!{nadekoId}> "; var nickMention = $"<@!{nadekoId}> ";
string message; string message;

View File

@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Games
else if ((pick == 0 && nadekoPick == 1) || else if ((pick == 0 && nadekoPick == 1) ||
(pick == 1 && nadekoPick == 2) || (pick == 1 && nadekoPick == 2) ||
(pick == 2 && nadekoPick == 0)) (pick == 2 && nadekoPick == 0))
msg = $"{NadekoBot.Client.CurrentUser().Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}"; msg = $"{NadekoBot.Client.CurrentUser.Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}";
else else
msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}"; msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}";

View File

@ -137,7 +137,7 @@ namespace NadekoBot.Modules.Help
} }
helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.GetPrefix())} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.GetPrefix())}"); helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.GetPrefix())} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.GetPrefix())}");
} }
helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser().Username , "@BotName"); helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser.Username , "@BotName");
File.WriteAllText("../../docs/Commands List.md", helpstr.ToString()); File.WriteAllText("../../docs/Commands List.md", helpstr.ToString());
await Context.Channel.SendConfirmAsync("Commandlist Regenerated").ConfigureAwait(false); await Context.Channel.SendConfirmAsync("Commandlist Regenerated").ConfigureAwait(false);
} }

View File

@ -31,7 +31,7 @@ namespace NadekoBot.Modules.Utility
var channel = imsg.Channel as ITextChannel; var channel = imsg.Channel as ITextChannel;
if (channel == null) if (channel == null)
return; return;
if (msg.Author.Id == NadekoBot.Client.CurrentUser().Id) return; if (msg.Author.Id == NadekoBot.Client.CurrentUser.Id) return;
foreach (var subscriber in Subscribers) foreach (var subscriber in Subscribers)
{ {
var set = subscriber.Value; var set = subscriber.Value;

View File

@ -277,7 +277,7 @@ namespace NadekoBot.Modules.Utility
.WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg")) .WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg"))
.AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser().Id.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser.Id.ToString()).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true))
.AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true))

View File

@ -28,7 +28,7 @@ namespace NadekoBot
public static CommandService CommandService { get; private set; } public static CommandService CommandService { get; private set; }
public static CommandHandler CommandHandler { get; private set; } public static CommandHandler CommandHandler { get; private set; }
public static ShardedDiscordClient Client { get; private set; } public static DiscordShardedClient Client { get; private set; }
public static BotCredentials Credentials { get; private set; } public static BotCredentials Credentials { get; private set; }
public static GoogleApiService Google { get; private set; } public static GoogleApiService Google { get; private set; }
@ -59,7 +59,7 @@ namespace NadekoBot
_log.Info("Starting NadekoBot v" + StatsService.BotVersion); _log.Info("Starting NadekoBot v" + StatsService.BotVersion);
//create client //create client
Client = new ShardedDiscordClient(new DiscordSocketConfig Client = new DiscordShardedClient(new DiscordSocketConfig
{ {
AudioMode = Discord.Audio.AudioMode.Outgoing, AudioMode = Discord.Audio.AudioMode.Outgoing,
MessageCacheSize = 10, MessageCacheSize = 10,
@ -68,6 +68,8 @@ namespace NadekoBot
ConnectionTimeout = int.MaxValue ConnectionTimeout = int.MaxValue
}); });
Client.Log += Client_Log;
//initialize Services //initialize Services
CommandService = new CommandService(new CommandServiceConfig() { CommandService = new CommandService(new CommandServiceConfig() {
CaseSensitiveCommands = false CaseSensitiveCommands = false
@ -114,6 +116,15 @@ namespace NadekoBot
Console.WriteLine(await Stats.Print().ConfigureAwait(false)); Console.WriteLine(await Stats.Print().ConfigureAwait(false));
} }
private Task Client_Log(LogMessage arg)
{
_log.Warn(arg.Message);
if (arg.Exception != null)
_log.Warn(arg.Exception);
return Task.CompletedTask;
}
public async Task RunAndBlockAsync(params string[] args) public async Task RunAndBlockAsync(params string[] args)
{ {
await RunAsync(args).ConfigureAwait(false); await RunAsync(args).ConfigureAwait(false);

View File

@ -32,7 +32,7 @@ namespace NadekoBot.Services
{ {
public const int GlobalCommandsCooldown = 1500; public const int GlobalCommandsCooldown = 1500;
private readonly ShardedDiscordClient _client; private readonly DiscordShardedClient _client;
private readonly CommandService _commandService; private readonly CommandService _commandService;
private readonly Logger _log; private readonly Logger _log;
@ -46,7 +46,7 @@ namespace NadekoBot.Services
public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>(); public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>();
private Timer clearUsersOnShortCooldown { get; } private Timer clearUsersOnShortCooldown { get; }
public CommandHandler(ShardedDiscordClient client, CommandService commandService) public CommandHandler(DiscordShardedClient client, CommandService commandService)
{ {
_client = client; _client = client;
_commandService = commandService; _commandService = commandService;

View File

@ -1,4 +1,5 @@
using Discord; using Discord;
using Discord.WebSocket;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -11,7 +12,7 @@ namespace NadekoBot.Services.Impl
{ {
public class StatsService : IStatsService public class StatsService : IStatsService
{ {
private ShardedDiscordClient client; private DiscordShardedClient client;
private DateTime started; private DateTime started;
public const string BotVersion = "1.1.0"; public const string BotVersion = "1.1.0";
@ -30,7 +31,7 @@ namespace NadekoBot.Services.Impl
Timer carbonitexTimer { get; } Timer carbonitexTimer { get; }
public StatsService(ShardedDiscordClient client, CommandHandler cmdHandler) public StatsService(DiscordShardedClient client, CommandHandler cmdHandler)
{ {
this.client = client; this.client = client;
@ -39,15 +40,6 @@ namespace NadekoBot.Services.Impl
this.client.MessageReceived += _ => Task.FromResult(MessageCounter++); this.client.MessageReceived += _ => Task.FromResult(MessageCounter++);
cmdHandler.CommandExecuted += (_, e) => Task.FromResult(CommandsRan++); cmdHandler.CommandExecuted += (_, e) => Task.FromResult(CommandsRan++);
this.client.Disconnected += _ => Reset();
this.client.Connected += () =>
{
var guilds = this.client.GetGuilds();
_textChannels = guilds.Sum(g => g.Channels.Where(cx => cx is ITextChannel).Count());
_voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels;
};
this.client.ChannelCreated += (c) => this.client.ChannelCreated += (c) =>
{ {
if (c is ITextChannel) if (c is ITextChannel)
@ -90,7 +82,7 @@ namespace NadekoBot.Services.Impl
{ {
using (var content = new FormUrlEncodedContent( using (var content = new FormUrlEncodedContent(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "servercount", this.client.GetGuildsCount().ToString() }, { "servercount", this.client.GetGuildCount().ToString() },
{ "key", NadekoBot.Credentials.CarbonKey }})) { "key", NadekoBot.Credentials.CarbonKey }}))
{ {
content.Headers.Clear(); content.Headers.Clear();
@ -103,16 +95,24 @@ namespace NadekoBot.Services.Impl
catch { } catch { }
}, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
} }
public void Initialize()
{
var guilds = this.client.GetGuilds();
_textChannels = guilds.Sum(g => g.Channels.Where(cx => cx is ITextChannel).Count());
_voiceChannels = guilds.Sum(g => g.Channels.Count) - _textChannels;
}
public Task<string> Print() public Task<string> Print()
{ {
var curUser = client.CurrentUser(); var curUser = client.CurrentUser;
return Task.FromResult($@" return Task.FromResult($@"
Author: [{Author}] | Library: [{Library}] Author: [{Author}] | Library: [{Library}]
Bot Version: [{BotVersion}] Bot Version: [{BotVersion}]
Bot ID: {curUser.Id} Bot ID: {curUser.Id}
Owner ID(s): {string.Join(", ", NadekoBot.Credentials.OwnerIds)} Owner ID(s): {string.Join(", ", NadekoBot.Credentials.OwnerIds)}
Uptime: {GetUptimeString()} Uptime: {GetUptimeString()}
Servers: {client.GetGuildsCount()} | TextChannels: {TextChannels} | VoiceChannels: {VoiceChannels} Servers: {client.GetGuildCount()} | TextChannels: {TextChannels} | VoiceChannels: {VoiceChannels}
Commands Ran this session: {CommandsRan} Commands Ran this session: {CommandsRan}
Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]"); Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]");
} }

View File

@ -107,7 +107,7 @@ namespace NadekoBot
public DiscordSocketClient MainClient => public DiscordSocketClient MainClient =>
Clients[0]; Clients[0];
public SocketSelfUser CurrentUser() => public SocketSelfUser CurrentUser =>
Clients[0].CurrentUser; Clients[0].CurrentUser;
public IEnumerable<SocketGuild> GetGuilds() => public IEnumerable<SocketGuild> GetGuilds() =>
@ -182,22 +182,7 @@ namespace NadekoBot
public Task SetStatus(SettableUserStatus status) => Task.WhenAll(Clients.Select(ms => ms.SetStatusAsync(SettableUserStatusToUserStatus(status)))); public Task SetStatus(SettableUserStatus status) => Task.WhenAll(Clients.Select(ms => ms.SetStatusAsync(SettableUserStatusToUserStatus(status))));
private static UserStatus SettableUserStatusToUserStatus(SettableUserStatus sus)
{
switch (sus)
{
case SettableUserStatus.Online:
return UserStatus.Online;
case SettableUserStatus.Invisible:
return UserStatus.Invisible;
case SettableUserStatus.Idle:
return UserStatus.AFK;
case SettableUserStatus.Dnd:
return UserStatus.DoNotDisturb;
}
return UserStatus.Online;
}
} }
public enum SettableUserStatus public enum SettableUserStatus

View File

@ -203,7 +203,7 @@ namespace NadekoBot.Extensions
await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false);
public static bool IsAuthor(this IUserMessage msg) => public static bool IsAuthor(this IUserMessage msg) =>
NadekoBot.Client.CurrentUser().Id == msg.Author.Id; NadekoBot.Client.CurrentUser.Id == msg.Author.Id;
public static IEnumerable<IUser> Members(this IRole role) => public static IEnumerable<IUser> Members(this IRole role) =>
role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty<IUser>(); role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty<IUser>();