You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Fox-V3/chatter/chatter.py

129 lines
3.9 KiB

import asyncio
from typing import List, Union
import discord
from discord.ext import commands
from redbot.core import Config
from redbot.core.bot import Red
7 years ago
from .source import ChatBot
from .source.trainers import ListTrainer
7 years ago
from datetime import datetime,timedelta
class Chatter:
"""
This cog trains a chatbot that will talk like members of your Guild
"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=6710497116116101114)
default_global = {}
7 years ago
default_guild = {
"whitelist": None,
"days": 1
}
7 years ago
self.chatbot = ChatBot("ChatterBot")
self.chatbot.set_trainer(ListTrainer)
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
7 years ago
self.loop = asyncio.get_event_loop()
7 years ago
async def _get_conversation(self, ctx, in_channel: discord.TextChannel):
"""
7 years ago
Compiles all conversation in the Guild this bot can get it's hands on
Currently takes a stupid long time
Returns a list of text
"""
out = []
7 years ago
after = datetime.today() - timedelta(days=(await self.config.guild(ctx.guild).days()))
7 years ago
for channel in ctx.guild.text_channels:
if in_channel:
channel = in_channel
await ctx.send("Gathering {}".format(channel.mention))
try:
7 years ago
async for message in channel.history(limit=None, reverse=True, after=after):
out.append(message.content)
except discord.Forbidden:
pass
except discord.HTTPException:
pass
7 years ago
if in_channel:
break
return out
7 years ago
def _train(self, data):
try:
self.chatbot.train(data)
except:
return False
return True
7 years ago
@commands.group()
async def chatter(self, ctx: commands.Context):
"""
Base command for this cog. Check help for the commands list.
"""
if ctx.invoked_subcommand is None:
await ctx.send_help()
7 years ago
@chatter.command()
async def age(self, ctx: commands.Context, days: int):
"""
Sets the number of days to look back
Will train on 1 day otherwise
"""
await self.config.guild(ctx.guild).days.set(days)
await ctx.send("Success")
@chatter.command()
async def train(self, ctx: commands.Context, channel: discord.TextChannel = None):
"""
Trains the bot based on language in this guild
"""
7 years ago
conversation = await self._get_conversation(ctx, channel)
if not conversation:
await ctx.send("Failed to gather training data")
return
7 years ago
await ctx.send("Gather successful! Training begins now\n(**This will take a long time, be patient**)")
future = await self.loop.run_in_executor(None, self._train, conversation)
if future:
7 years ago
await ctx.send("Training successful!")
else:
7 years ago
await ctx.send("Error occurred :(")
async def on_message(self, message):
"""
Credit to https://github.com/Twentysix26/26-Cogs/blob/master/cleverbot/cleverbot.py
for on_message recognition of @bot
"""
author = message.author
channel = message.channel
if message.author.id != self.bot.user.id:
to_strip = "@" + author.guild.me.display_name + " "
text = message.clean_content
if not text.startswith(to_strip):
return
text = text.replace(to_strip, "", 1)
async with channel.typing():
response = self.chatbot.get_response(text)
if response:
await channel.send(response)
else:
await channel.send(":thinking:")