# AIML files, or load a precompiled "brain" that was created from a # previous run. If no brain file is available, we force a reload of # the AIML files. brainLoaded = False forceReload = False while not brainLoaded: if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"): # Use the Kernel's bootstrap() method to initialize the Kernel. The # optional learnFiles argument is a file (or list of files) to load. # The optional commands argument is a command (or list of commands) # to run after the files are loaded. kern.bootstrap(learnFiles="std-startup.xml", commands="load aiml b") brainLoaded = True # Now that we've loaded the brain, save it to speed things up for # next time. kern.saveBrain("standard.brn") else: # Attempt to load the brain file. If it fails, fall back on the Reload # method. try: # The optional branFile argument specifies a brain file to load. kern.bootstrap(brainFile="standard.brn") brainLoaded = True except: forceReload = True # Enter the main input/output loop. print("\nINTERACTIVE MODE (ctrl-c to exit)") while (True): inpt = input("> ")
class ChatterBot(commands.Cog): # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings, prefix: str = '$'): self.bot = bot self.settings = settings self.prefix = prefix self.waitTime = 4 # Wait time in seconds self.botDir = 'standard' self.botBrain = 'standard.brn' self.botList = [] self.ownerName = "CorpNewt" self.ownerGender = "man" self.timeout = 3 self.chatBot = Kernel() global Utils, DisplayName Utils = self.bot.get_cog("Utils") DisplayName = self.bot.get_cog("DisplayName") def _load(self): # We're ready - let's load the bots if not os.path.exists(self.botBrain): # No brain, let's learn and create one files = os.listdir(self.botDir) for file in files: # Omit files starting with . if file.startswith("."): continue self.chatBot.learn(self.botDir + '/' + file) # Save brain self.chatBot.saveBrain(self.botBrain) else: # Already have a brain - load it self.chatBot.bootstrap(brainFile=self.botBrain) # Learned by this point - let's set our owner's name/gender # Start the convo self.chatBot.respond('Hello') # Bot asks for our Name self.chatBot.respond('My name is {}'.format(self.ownerName)) # Bot asks for our gender self.chatBot.respond('I am a {}'.format(self.ownerGender)) def canChat(self, server): if not server: return True # No settings to check here # Check if we can chat lastTime = int(self.settings.getServerStat(server, "LastChat", 0)) threshold = int(self.waitTime) currentTime = int(time.time()) if currentTime < (int(lastTime) + int(threshold)): return False # If we made it here - set the LastPicture method self.settings.setServerStat(server, "LastChat", int(time.time())) return True async def killcheck(self, message): ignore = False for cog in self.bot.cogs: real_cog = self.bot.get_cog(cog) if real_cog == self: # Don't check ourself continue try: check = await real_cog.test_message(message) except AttributeError: try: check = await real_cog.message(message) except AttributeError: continue if not type(check) is dict: # Force it to be a dict check = {} try: if check['Ignore']: ignore = True except KeyError: pass return ignore async def message(self, message): # Check the message and see if we should allow it - always yes. # This module doesn't need to cancel messages. msg = message.content chatChannel = self.settings.getServerStat(message.guild, "ChatChannel") the_prefix = await self.bot.command_prefix(self.bot, message) if chatChannel and not message.author.id == self.bot.user.id and not msg.startswith( the_prefix): # We have a channel # Now we check if we're hungry/dead and respond accordingly if await self.killcheck(message): return {"Ignore": True, "Delete": False} if str(message.channel.id) == str(chatChannel): # We're in that channel! #ignore = True # Strip prefix msg = message.content ctx = await self.bot.get_context(message) await self._chat(ctx, msg) return {'Ignore': False, 'Delete': False} @commands.command(pass_context=True) async def setchatchannel(self, ctx, *, channel: discord.TextChannel = None): """Sets the channel for bot chatter.""" if not await Utils.is_admin_reply(ctx): return if channel == None: self.settings.setServerStat(ctx.guild, "ChatChannel", "") msg = 'Chat channel removed - must use the `{}chat [message]` command to chat.'.format( ctx.prefix) await ctx.send(msg) return # If we made it this far - then we can add it self.settings.setServerStat(ctx.guild, "ChatChannel", channel.id) msg = 'Chat channel set to **{}**.'.format(channel.name) await ctx.send(msg) @setchatchannel.error async def setchatchannel_error(self, error, ctx): # do stuff msg = 'setchatchannel Error: {}'.format(error) await ctx.send(msg) @commands.command(pass_context=True) async def chat(self, ctx, *, message=None): """Chats with the bot.""" await self._chat(ctx, message) async def _chat(self, ctx, message): # Check if we're suppressing @here and @everyone mentions message = DisplayName.clean_message(message, bot=self.bot, server=ctx.guild) if message == None: return if not self.canChat(ctx.guild): return await ctx.trigger_typing() msg = self.chatBot.respond(message) msg = msg if msg else "I don't know what to say..." await ctx.send(msg)
def create_brain(): kernel = Kernel() kernel.bootstrap(learnFiles="startup.xml", commands="load aiml b") kernel.saveBrain("brain.brn")
from aiml import Kernel import os import ast kernel = Kernel() # read bot properties from files bot_properties = ast.literal_eval(open('bot.properties', 'r', encoding="utf-8").read()) kernel._botPredicates = bot_properties # read brain file if availble, else learn aiml file #brain_file = "bot_brain_alice.brn" brain_file = "bot_brain_standard.brn" if os.path.isfile(brain_file): kernel.bootstrap(brainFile=brain_file) else: kernel.bootstrap(learnFiles="std-startup.xml", commands="load aiml b") kernel.saveBrain(brain_file) #kernel.resetBrain() def reply(text, sessionId = 2215): return kernel.respond(text, sessionId)
a log file is highly recommended. """ # import aiml from aiml import Kernel # Use PyAiml dev # Create the kernels kern1 = Kernel() kern1.verbose(False) kern2 = Kernel() kern2.verbose(False) # Initialize the kernels print("Initializing Kernel #1") kern1.bootstrap(learnFiles="std-startup.xml", commands="load aiml b") kern1.saveBrain("standard.brn") print("\nInitializing Kernel #2") kern2.bootstrap(brainFile="standard.brn") # Start the bots off with some basic input. response = "askquestion" # Off they go! while True: response = kern1.respond(response).strip() print("1:", response) response = kern2.respond(response).strip() print("2:", response) # If the robots have run out of things to say, force one of them # to break the ice. if response == "":
class ChatterBot(commands.Cog): # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings, prefix: str = '$'): self.bot = bot self.settings = settings self.prefix = prefix self.waitTime = 4 # Wait time in seconds self.botDir = 'standard' self.botBrain = 'standard.brn' self.botList = [] self.ownerName = "NvStar" self.ownerGender = "man" self.timeout = 3 self.chatBot = Kernel() global Utils, DisplayName Utils = self.bot.get_cog("Utils") DisplayName = self.bot.get_cog("DisplayName") def _load(self): # We're ready - let's load the bots if not os.path.exists(self.botBrain): # No brain, let's learn and create one files = os.listdir(self.botDir) for file in files: # Omit files starting with . if file.startswith("."): continue self.chatBot.learn(self.botDir + '/' + file) # Save brain self.chatBot.saveBrain(self.botBrain) else: # Already have a brain - load it self.chatBot.bootstrap(brainFile=self.botBrain) # Learned by this point - let's set our owner's name/gender # Start the convo self.chatBot.respond('Hello') # Bot asks for our Name self.chatBot.respond('My name is {}'.format(self.ownerName)) # Bot asks for our gender self.chatBot.respond('I am a {}'.format(self.ownerGender)) def canChat(self, server): if not server: return True # No settings to check here # Check if we can chat lastTime = int(self.settings.getServerStat(server, "LastChat", 0)) threshold = int(self.waitTime) currentTime = int(time.time()) if currentTime < (int(lastTime) + int(threshold)): return False # If we made it here - set the LastPicture method self.settings.setServerStat(server, "LastChat", int(time.time())) return True async def killcheck(self, message): ignore = False for cog in self.bot.cogs: real_cog = self.bot.get_cog(cog) if real_cog == self: # Don't check ourself continue try: check = await real_cog.test_message(message) except AttributeError: try: check = await real_cog.message(message) except AttributeError: continue if not type(check) is dict: # Force it to be a dict check = {} try: if check['Ignore']: ignore = True except KeyError: pass return ignore async def message(self, message): # Check the message and see if we should allow it - always yes. # This module doesn't need to cancel messages. msg = message.content chatChannel = self.settings.getServerStat(message.guild, "ChatChannel") the_prefix = await self.bot.command_prefix(self.bot, message) if chatChannel and not message.author.id == self.bot.user.id and not msg.startswith( the_prefix): # We have a channel # Now we check if we're hungry/dead and respond accordingly if await self.killcheck(message): return {"Ignore": True, "Delete": False} if str(message.channel.id) == str(chatChannel): # We're in that channel! #ignore = True # Strip prefix msg = message.content ctx = await self.bot.get_context(message) await self._chat(ctx, msg) return {'Ignore': False, 'Delete': False} @commands.command(pass_context=True) async def setchatchannel(self, ctx, *, channel: discord.TextChannel = None): """Set channel untuk chatting dengan bot (admin-only). Bot hanya merespon dengan bahasa inggris Fitur ini belum sempurna karena masih berbahasa inggris. Tapi masih bisa di coba. Chat bot ini di adopsi dari A.L.I.C.E Artificial Linguistic Internet Computer Entity""" if not await Utils.is_admin_reply(ctx): return # isOwner = self.settings.isOwner(ctx.author) # if isOwner == None: # msg = 'Aku belum ada owner.' # return await ctx.send(msg) # elif isOwner == False: # msgText = ["Siapa yaa?\nKamu bukan owner ku", # "Kamu bukan owner ku", # "Hus hus, jangan main main sama command ini", # "Command ini bahaya loh dek, jangan main main!", # "ikjdfahguiyaewgkljasdcbngiuefabhg\nkamu bukan owner ku!!!"] # msg = random.choice(msgText) if channel == None: self.settings.setServerStat(ctx.guild, "ChatChannel", "") msg = 'Chat channel removed - must use the `{}chat [message]` command to chat.'.format( ctx.prefix) await ctx.send(msg) return # If we made it this far - then we can add it self.settings.setServerStat(ctx.guild, "ChatChannel", channel.id) msg = 'Chat channel set to **{}**.'.format(channel.name) await ctx.send(msg) @setchatchannel.error async def setchatchannel_error(self, error, ctx): # do stuff msg = 'setchatchannel Error: {}'.format(error) await ctx.send(msg) @commands.command(pass_context=True) async def chat(self, ctx, *, message=None): """Chat dengat bot. Bot hanya merespon dengan bahasa inggris Fitur ini belum sempurna karena masih berbahasa inggris. Tapi masih bisa di coba. Chat bot ini di adopsi dari A.L.I.C.E Artificial Linguistic Internet Computer Entity""" await self._chat(ctx, message) async def _chat(self, ctx, message): # Check if we're suppressing @here and @everyone mentions message = DisplayName.clean_message(message, bot=self.bot, server=ctx.guild) if message == None: return if not self.canChat(ctx.guild): return await ctx.trigger_typing() msg = self.chatBot.respond(message) msg = msg if msg else "I don't know what to say..." if len(msg) > 2000: msg = msg[:1997] + "..." # Fix for > 2000 chars await ctx.send(msg)