def start(): kernel = Kernel() kernel.verbose(False) if isfile(FILE_PATH+"aimlFiles\\brain.brn"): kernel.bootstrap(brainFile=FILE_PATH+"aimlFiles\\brain.brn") else: print("Please run brain.py file present in aimlFiles directory") exit() return kernel
class TestEncoding( unittest.TestCase ): longMessage = True def setUp(self): self.k = Kernel() self.k.bootstrap( learnFiles='encoding.aiml', chdir=os.path.dirname(__file__) ) def tearDown(self): del self.k def _testTag(self, input_, outputList, name=None, encoding='utf-8'): """Test by feeding the Kernel 'input'. If the result matches any of the strings in 'outputList', the test passes. """ print( b"Testing <" + (name or input_).encode(encoding) + b">") response = self.k._cod.dec( self.k.respond( self.k._cod.enc(input_) ) ) self.assertIn( response, outputList, msg="input=%s"%input_ ) def test01_utf8( self ): '''Test literal pattern''' self._testTag( u'pattern with eñe', [u"pattern #1 matched!"]) def test02_utf8( self ): '''Test star pattern''' self._testTag( u'pattern with Á', [u"pattern #2 matched: Á"]) def test03_noencoding( self ): '''Test unencoded strings''' self.k.setTextEncoding( False ) self._testTag( u'pattern with eñe', [u"pattern #1 matched!"]) self._testTag( u'pattern with Á', [u"pattern #2 matched: Á"]) def test04_iso8859( self ): enc = 'iso-8859-1' self.k.setTextEncoding( enc ) self._testTag( u'pattern with Á', [u"pattern #2 matched: Á"], encoding=enc)
class TestKernel(unittest.TestCase): longMessage = True def setUp(self): self.k = Kernel() testfile = os.path.join(os.path.dirname(__file__), "self-test.aiml") self.k.bootstrap(learnFiles=testfile) def tearDown(self): del self.k def _testTag(self, tag, input_, outputList): """Tests 'tag' by feeding the Kernel 'input'. If the result matches any of the strings in 'outputList', the test passes. """ print("Testing <" + tag + ">", end='\n') # Send the input and collect the output response = self.k._cod.dec(self.k.respond(self.k._cod.enc(input_))) # Check that output is as expected self.assertIn(response, outputList, msg="input=%s" % input_) def test01_bot(self): self._testTag('bot', 'test bot', ["My name is Nameless"]) def test02_condition(self): self.k.setPredicate('gender', 'male') self._testTag('condition test #1', 'test condition name value', ['You are handsome']) self.k.setPredicate('gender', 'female') self._testTag('condition test #2', 'test condition name value', ['']) self._testTag('condition test #3', 'test condition name', ['You are beautiful']) self.k.setPredicate('gender', 'robot') self._testTag('condition test #4', 'test condition name', ['You are genderless']) self._testTag('condition test #5', 'test condition', ['You are genderless']) self.k.setPredicate('gender', 'male') self._testTag('condition test #6', 'test condition', ['You are handsome']) def test03_date(self): # the date test will occasionally fail if the original and "test" # times cross a second boundary. There's no good way to avoid # this problem and still do a meaningful test, so we simply # provide a friendly message to be printed if the test fails. date_warning = """ NOTE: the <date> test will occasionally report failure even if it succeeds. So long as the response looks like a date/time string, there's nothing to worry about. """ if not self._testTag('date', 'test date', ["The date is %s" % time.asctime()]): print(date_warning) def test04_case(self): self._testTag('formal', 'test formal', ["Formal Test Passed"]) self._testTag('lowercase', 'test lowercase', ["The Last Word Should Be lowercase"]) self._testTag('sentence', "test sentence", ["My first letter should be capitalized."]) self._testTag('uppercase', 'test uppercase', ["The Last Word Should Be UPPERCASE"]) def test05_gender(self): self._testTag('gender', 'test gender', ["He'd told her he heard that her hernia is history"]) def test06_getset(self): self._testTag('get/set', 'test get and set', ["I like cheese. My favorite food is cheese"]) def test07_notimplemented(self): self._testTag('gossip', 'test gossip', ["Gossip is not yet implemented"]) self._testTag('javascript', 'test javascript', ["Javascript is not yet implemented"]) def test08_id(self): self._testTag('id', 'test id', ["Your id is _global"]) def test09_input(self): self._testTag('input', 'test input', ['You just said: test input']) def test10_person(self): self._testTag( 'person', 'test person', ['HE think i knows that my actions threaten him and his.']) self._testTag( 'person2', 'test person2', ['YOU think me know that my actions threaten you and yours.']) self._testTag('person2 (no contents)', 'test person2 I Love Lucy', ['YOU Love Lucy']) def test11_random(self): self._testTag('random', 'test random', ["response #1", "response #2", "response #3"]) self._testTag('random empty', 'test random empty', ["Nothing here!"]) def test12_size(self): self._testTag('size', "test size", ["I've learned %d categories" % self.k.numCategories()]) def test13_srai(self): self._testTag('sr', "test sr test srai", ["srai results: srai test passed"]) self._testTag('sr nested', "test nested sr test srai", ["srai results: srai test passed"]) self._testTag('srai', "test srai", ["srai test passed"]) self._testTag('srai infinite', "test srai infinite", [""]) def test13_star(self): self._testTag('star test #1', 'You should test star begin', ['Begin star matched: You should']) self._testTag('star test #2', 'test star creamy goodness middle', ['Middle star matched: creamy goodness']) self._testTag('star test #3', 'test star end the credits roll', ['End star matched: the credits roll']) self._testTag( 'star test #4', 'test star having multiple stars in a pattern makes me extremely happy', [ 'Multiple stars matched: having, stars in a pattern, extremely happy' ]) def test14_that(self): self._testTag('system', "test system", ["The system says hello!"]) # This one must go right after the previous one self._testTag('that test #1', "test that", ["I just said: The system says hello!"]) self._testTag('that test #2', "test that", ["I have already answered this question"]) def test15_thatstar(self): self._testTag('thatstar test #1', "test thatstar", ["I say beans"]) self._testTag('thatstar test #2', "test thatstar", ["I just said \"beans\""]) self._testTag('thatstar test #3', "test thatstar multiple", ['I say beans and franks for everybody']) self._testTag('thatstar test #4', "test thatstar multiple", ['Yes, beans and franks for all!']) def test15_think(self): self._testTag('think', "test think", [""]) def test16_topic(self): self.k.setPredicate("topic", "fruit") self._testTag('topic', "test topic", ["We were discussing apples and oranges"]) self.k.setPredicate("topic", "Soylent Green") self._testTag('topicstar test #1', 'test topicstar', ["Solyent Green is made of people!"]) self.k.setPredicate("topic", "Soylent Ham and Cheese") self._testTag('topicstar test #2', 'test topicstar multiple', ["Both Soylents Ham and Cheese are made of people!"]) def test17_unicode(self): self._testTag('unicode support', u"тгио╨ц", [u"Hey, you speak Chinese! тгио╨ц"]) def test18_version(self): self._testTag('version', 'test version', ["PyAIML is version %s" % self.k.version()]) def test18_whitespace(self): self._testTag('whitespace preservation', 'test whitespace', [ "Extra Spaces\n Rule! (but not in here!) But Here They Do!" ])
if (args.gtts): try: from gtts import gTTS from pygame import mixer voice = "gTTS" except ImportError: import pyttsx print("\nInstall gTTS and pygame to use this feature." + "\nUsing pyttsx\n") else: import pyttsx3 kernel = Kernel() if os.path.isfile("bot_brain.brn"): kernel.bootstrap(brainFile="bot_brain.brn") else: kernel.bootstrap(learnFiles="std-startup.xml", commands="load aiml b") # kernel.saveBrain("bot_brain.brn") # kernel now ready for use while True: if mode == "voice": response = listen() else: response = raw_input("Talk to J.A.R.V.I.S : ") if response.lower().replace(" ", "") in terminate: break jarvis_speech = kernel.respond(response) print("J.A.R.V.I.S: ") + jarvis_speech speak(jarvis_speech)
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)
them in a cyclic loop. A lot of output is generated; piping the results to 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.
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)
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)