Cleverbot reworked

This commit is contained in:
Kwoth
2016-11-08 19:27:44 +01:00
parent bca44259fb
commit eab28824ef
13 changed files with 562 additions and 132 deletions

View File

@@ -5,6 +5,7 @@ using NadekoBot.Services;
using NadekoBot.Services.Database;
using Newtonsoft.Json;
using NLog;
using Services.CleverBotApi;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -21,26 +22,27 @@ namespace NadekoBot.Modules.Games
[Group]
public class CleverBotCommands
{
private Logger _log { get; }
private static Logger _log { get; }
class CleverAnswer {
public string Status { get; set; }
public string Response { get; set; }
}
public CleverBotCommands()
{
_log = LogManager.GetCurrentClassLogger();
}
//user#discrim is the key
public static ConcurrentHashSet<string> ChannelsInConversation { get; } = new ConcurrentHashSet<string>();
public static ConcurrentHashSet<ulong> CleverbotGuilds { get; } = new ConcurrentHashSet<ulong>();
public static ConcurrentDictionary<ulong, ChatterBotSession> CleverbotGuilds { get; } = new ConcurrentDictionary<ulong, ChatterBotSession>();
static CleverBotCommands()
{
_log = LogManager.GetCurrentClassLogger();
using (var uow = DbHandler.UnitOfWork())
{
CleverbotGuilds = new ConcurrentHashSet<ulong>(uow.GuildConfigs.GetAll().Where(gc => gc.CleverbotEnabled).Select(gc => gc.GuildId));
var bot = ChatterBotFactory.Create(ChatterBotType.CLEVERBOT);
CleverbotGuilds = new ConcurrentDictionary<ulong, ChatterBotSession>(
uow.GuildConfigs.GetAll()
.Where(gc => gc.CleverbotEnabled)
.ToDictionary(gc => gc.GuildId, gc => bot.CreateSession()));
}
}
@@ -50,9 +52,8 @@ namespace NadekoBot.Modules.Games
if (channel == null)
return false;
var nick = msg.Channel.Id + "NadekoBot";
if (!ChannelsInConversation.Contains(nick) && !CleverbotGuilds.Contains(channel.Guild.Id))
ChatterBotSession cleverbot;
if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot))
return false;
var nadekoId = NadekoBot.Client.GetCurrentUser().Id;
@@ -61,11 +62,11 @@ namespace NadekoBot.Modules.Games
string message;
if (msg.Content.StartsWith(normalMention))
{
message = msg.Content.Substring(normalMention.Length);
message = msg.Content.Substring(normalMention.Length).Trim();
}
else if (msg.Content.StartsWith(nickMention))
{
message = msg.Content.Substring(nickMention.Length);
message = msg.Content.Substring(nickMention.Length).Trim();
}
else
{
@@ -74,98 +75,51 @@ namespace NadekoBot.Modules.Games
await msg.Channel.TriggerTypingAsync().ConfigureAwait(false);
using (var http = new HttpClient())
var response = await cleverbot.Think(message).ConfigureAwait(false);
try
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "user", NadekoBot.Credentials.CleverbotApiUser},
{ "key", NadekoBot.Credentials.CleverbotApiKey},
{ "nick", nick},
{ "text", message},
});
var res = await http.PostAsync("https://cleverbot.io/1.0/ask", content).ConfigureAwait(false);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
try
{
var answer = JsonConvert.DeserializeObject<CleverAnswer>(await res.Content.ReadAsStringAsync().ConfigureAwait(false));
try
{
await msg.Channel.SendMessageAsync(WebUtility.HtmlDecode(answer.Response)).ConfigureAwait(false);
}
catch
{
await msg.Channel.SendMessageAsync(answer.Response).ConfigureAwait(false); // try twice :\
}
}
catch { }
return true;
}
return false;
await msg.Channel.SendMessageAsync(response).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Warn(ex, "Eror sending response");
await msg.Channel.SendMessageAsync(response).ConfigureAwait(false); // try twice :\
}
return true;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequirePermission(ChannelPermission.ManageMessages)]
public async Task Cleverbot(IUserMessage imsg, string all = null)
public async Task Cleverbot(IUserMessage imsg)
{
var channel = (ITextChannel)imsg.Channel;
if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.CleverbotApiKey) ||
string.IsNullOrWhiteSpace(NadekoBot.Credentials.CleverbotApiKey))
{
await channel.SendMessageAsync(":anger: `Bot owner didn't setup Cleverbot Api keys. Session will not start.`").ConfigureAwait(false);
return;
}
if (all?.Trim().ToLowerInvariant() == "all")
ChatterBotSession throwaway;
if (CleverbotGuilds.TryRemove(channel.Guild.Id, out throwaway))
{
var cleverbotEnabled = CleverbotGuilds.Add(channel.Guild.Id);
if (!cleverbotEnabled)
CleverbotGuilds.TryRemove(channel.Guild.Id);
using (var uow = DbHandler.UnitOfWork())
{
uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, cleverbotEnabled);
uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, false);
await uow.CompleteAsync().ConfigureAwait(false);
}
await channel.SendMessageAsync($"{imsg.Author.Mention} `{(cleverbotEnabled ? "Enabled" : "Disabled")} cleverbot for all users.`").ConfigureAwait(false);
await channel.SendMessageAsync($"{imsg.Author.Mention} `Disabled cleverbot on this server.`").ConfigureAwait(false);
return;
}
var cleverbot = ChatterBotFactory.Create(ChatterBotType.CLEVERBOT);
var session = cleverbot.CreateSession();
var nick = channel.Id + "NadekoBot";
CleverbotGuilds.TryAdd(channel.Guild.Id, session);
if (ChannelsInConversation.TryRemove(nick))
using (var uow = DbHandler.UnitOfWork())
{
await channel.SendMessageAsync($"{imsg.Author.Mention} `I will no longer reply to your messages starting with my mention.`").ConfigureAwait(false);
return;
uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, true);
await uow.CompleteAsync().ConfigureAwait(false);
}
using (var http = new HttpClient())
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{ "user", NadekoBot.Credentials.CleverbotApiUser},
{ "key", NadekoBot.Credentials.CleverbotApiKey},
{ "nick", nick},
});
var res = await http.PostAsync("https://cleverbot.io/1.0/create", content).ConfigureAwait(false);
if (res.StatusCode != System.Net.HttpStatusCode.OK)
{
await channel.SendMessageAsync($"{imsg.Author.Mention} `Something went wrong in starting your cleverbot session :\\`");
_log.Warn(await res.Content.ReadAsStringAsync());
return;
}
ChannelsInConversation.Add(nick);
}
await channel.SendMessageAsync($"{imsg.Author.Mention} `I will reply to your messages starting with my mention.`").ConfigureAwait(false);
await channel.SendMessageAsync($"{imsg.Author.Mention} `Enabled cleverbot on this server.`").ConfigureAwait(false);
}
}
}
}