class RetrievalCustom(LogicAdapter): def __init__(self, chatbot, **kwargs): super().__init__(chatbot, **kwargs) self.language = kwargs.get('language', languages.ENG) self.cache = {} self.k = Kernel() self.k.learn("std-startup.xml") self.k.respond("load aiml b") def can_process(self, statement): response = self.process(statement) self.cache[statement.text] = response return response.confidence == 1 def process(self, statement, additional_response_selection_parameters=None): input_text = statement.text if input_text in self.cache: cached_result = self.cache[input_text] self.cache = {} return cached_result response_aiml = self.k.respond(input_text) # TODO: kernel.py 안에서 respond()에 없는 대답 input으로 넣으면 원래는 I don't know 등을 내뱉지만, 우리는 그걸 없앨거라서 # response 가 ""로 나오는 경우가 있음. # 그럴 때 _respond 에서 "Warning: No match" 어쩌고가 error로서 프린트 되는데 그거 지워야함 if response_aiml == "": #retrieval 안에 없을 때 txt = "No match aiml." response = Statement(text=txt) response.confidence = 0 else: response = Statement(text=response_aiml) response.confidence = 1 return response
# Hatter command line version, This doesn't require Flask from aiml import Kernel from os import listdir import sys files = listdir('standard') bot = Kernel() for file in files: bot.learn('standard/'+file) respon = ' ' print "Hatter> Hello , I am Tarrant the Hatter. Some people call me the Mad Hatter. Good to see you. Type \"bye\" to exit" while 1 : question=raw_input("You> ") reply=bot.respond(question) print "Hatter> ",reply if question=="bye": sys.exit(0)
from flask import g, session, request, render_template, flash from aiml import Kernel from os import listdir files = listdir('standard') #CONFIGURATION DEBUG = True #APP app = Flask(__name__) app.config.from_object(__name__) bot = Kernel() for file in files: bot.learn('standard/' + file) respon = ' ' @app.before_request def before_request(): g.respon = 'Hello , I am Tarrant the Hatter. Some people call me the Mad Hatter. Good to see you.' @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': reply = bot.respond(request.form['question']) return render_template('index.html', respon=reply) return render_template('index.html', respon=g.respon)
import os import sys curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) from aiml import Kernel from jieba_dic.keyword import keywords from find_college.findKey import find_college import QQChat import aiml_similarity as a2s this_path = os.path.dirname(os.path.realpath(__file__)) name = '' alice = Kernel() # alice.learn(os.path.join(this_path,"cn-test.aiml") alice.learn(os.path.join(this_path, '../local_scrap/local_cc.aiml')) alice.learn(os.path.join(this_path, "../local_scrap/local_cs.aiml")) alice.learn(os.path.join(this_path, "../local_scrap/who.aiml")) alice.learn(os.path.join(this_path, "../local_scrap/nk.aiml")) def similar_ans(question): # aiml_similarity模块判定,本模块可信度较高 answer, similar = a2s.respond(question) # answer为返回结果,similar记录相似度 if answer and similar >= 0.45: #print(answer) return answer # QQChat模块判定,本模块可信度较低,建议延后 answer, similar = QQChat.respond(question) # answer为返回结果,similar记录相似度 if answer and similar >= 0.4:
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)
from aiml import Kernel kernel = Kernel() kernel.learn('brain.aiml') print("Say Hello! and ask questions like, I want to know about loan") while True: print("Bot->", kernel.respond(input("User-> ")))
# -*- coding:utf-8 -*- from aiml import Kernel import config from metodos import sendMessage, getMe, sendChatAction from config import sudo import sys, time, os kernel = Kernel() kernel.learn(config.ia['mae']) kernel.respond(config.ia['cerebro']) def cmd(msg): if msg['text'].startswith('/add'): if msg['from']['id'] == sudo: text = msg['text'].replace('/add ', '') pergunta = text.split('|', 1)[0] resposta = text.split('|', 1)[1] sendMessage(msg['chat']['id'], escreva(pergunta, resposta)) time.sleep(2) os.execl(sys.executable, sys.executable, *sys.argv) def leia(arquivo): ### PEGA A ULTIMA LINHA aiml = open(arquivo, 'r') # abre o aquivo para leitura line = aiml.readlines() # le as linhas do arquivo line = '{}'.format( line[-1]) # pega a ultima linha e formata como string caso nao seja
def main(): args = parse_args() timeout = args.timeout # 初始化jb分词器 T.jieba_initialize() # 切换到语料库所在工作目录 mybot_path = './' os.chdir(mybot_path) mybot = Kernel() mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/std-startup.xml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/bye.aiml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/tools.aiml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/bad.aiml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/funny.aiml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/OrdinaryQuestion.aiml") mybot.learn( os.path.split(os.path.realpath(__file__))[0] + "/resources/Common conversation.aiml") if enable_chrome: question_obj = Value(ctypes.c_char_p, "".encode("utf-8")) browser_daemon = multiprocessing.Process(target=run_browser, args=(question_obj, )) browser_daemon.daemon = True browser_daemon.start() def __inner_job(): start = time.time() text_binary = analyze_current_screen_text( directory=data_directory, compress_level=image_compress_level[0]) keywords = get_text_from_image(image_data=text_binary, ) if not keywords: print("text not recognize") return true_flag, question, answers = parse_question_and_answer(keywords) #questions=question.decode('unicode-escape') #new_ans=[] #for ans in answers: # new_ans.append(ans.decode('unicode-escape')) print('-' * 72) print(question) print('-' * 72) print("\n".join(answers)) # notice browser if enable_chrome: with question_obj.get_lock(): question_obj.value = question keyboard.press("space") search_question = pre_process_question(question) summary = baidu_count(search_question, answers, timeout=timeout) summary_li = sorted(summary.items(), key=operator.itemgetter(1), reverse=True) data = [("选项", "同比")] for a, w in summary_li: data.append((a, w)) table = AsciiTable(data) print(table.table) print("*" * 72) if true_flag: print("肯定回答(**): ", summary_li[0][0]) print("否定回答( ): ", summary_li[-1][0]) else: print("肯定回答( ): ", summary_li[0][0]) print("否定回答(**): ", summary_li[-1][0]) print("*" * 72) ############################################################## input_message = question if len(input_message) > 60: print(mybot.respond("句子长度过长")) elif input_message.strip() == '': print(mybot.respond("无")) #print(input_message) message = T.wordSegment(input_message) # 去标点 #print('word Seg:' + message) #print('词性:') words = T.postag(input_message) if message == 'q': exit() else: response = mybot.respond(message) #print("=======") #print(response) #print("=======") if response == "": ans = mybot.respond('找不到答案') print('Eric:' + ans) # 百科搜索 elif response[0] == '#': # 匹配百科 if response.__contains__("searchbaike"): #print("searchbaike") #print(response) res = response.split(':') # 实体 entity = str(res[1]).replace(" ", "") # 属性 attr = str(res[2]).replace(" ", "") #print(entity + '<---->' + attr) ans = baike.query(entity, attr) # 如果命中答案 if type(ans) == list: print('Eric:' + QAT.ptranswer(ans, False)) elif ans.decode('utf-8').__contains__(u'::找不到'): # 百度摘要+Bing摘要 print("通用搜索") ans = search_summary.kwquery(input_message) # 匹配不到模版,通用查询 elif response.__contains__("NoMatchingTemplate"): #print("NoMatchingTemplate") ans = search_summary.kwquery(input_message, answers) if len(ans) == 0: print('Eric:' + '找不到答案') elif len(ans) > 1: print("不确定候选答案") print('Eric: ') for a in ans: print(a) else: print('Eric:' + ans[0]) # 匹配模版 else: print('Eric:' + response) end = time.time() print("use {0} 秒".format(end - start)) save_screen(directory=data_directory) while True: print(""" 请在答题开始前就运行程序, 答题开始的时候按Enter预测答案 """) enter = input("按Enter键开始,按ESC键退出...") print(enter) if enter == chr(27): break try: __inner_job() except Exception as e: print(str(e)) print("欢迎下次使用")
#/etc/bin/env python2 import time import aiml import os from aiml import Kernel from os import listdir import speech_recognition as sr import sys import pyttsx r = sr.Recognizer() files = listdir('aiml') bot = Kernel() for file in files: bot.learn('aiml/' + file) def botsay(str, end="\n"): print("Bucky :> " + str) engine = pyttsx.init() engine.say(str) engine.runAndWait() def readin(): #tempx = str(raw_input(msg)) with sr.Microphone() as source: print("Listening...") audio = r.listen(source) try: res = r.recognize_google(audio)
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)