def chat(request): try: client = str(request.GET["q"]).strip() except: msg = "hi" call = multiFunctionCall({"whoIs": whoIs, "getQues": getQues}) bot = Chat(pairs, reflections, call=call) bot.conversation["general"].append( "Hi, I am your stackExchange bot. What can I do for you?") bot.conversation["general"].append(client) reply = bot.respond(client, sessionID="general") bot.conversation["general"].append(reply) return HttpResponse(reply)
class WikipediaBrain(commands.Cog): def __init__(self, bot): self.bot = bot @register_call("whoIs") def who_is(self, ctx, session_id="general"): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return "I don't know about " + query template_file_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "chatbotTemplate", "chatbottemplate.template") chat = Chat(template_file_path) @commands.command(pass_context=True) async def chatbot(ctx, *, message): result = chat.respond(message) if (len(result) <= 2048): embed = discord.Embed(title="ChatBot AI", description=result, color=(0xF48D1)) await ctx.send(embed=embed) else: embedList = [] n = 2048 embedList = [result[i:i + n] for i in range(0, len(result), n)] for num, item in enumerate(embedList, start=1): if (num == 1): embed = discord.Embed(title="ChatBot AI", description=item, color=(0xF48D1)) embed.set_footer(text="Page {}".format(num)) await ctx.send(embed=embed) else: embed = discord.Embed(description=item, color=(0xF48D1)) embed.set_footer(text="Page {}".format(num)) await ctx.send(embed=embed)
class ChatbotAI(commands.Cog): """ (∩`-´)⊃━☆゚.*・。゚ dafuq is this? """ def __init__(self, bot): self.bot = bot @register_call('whoIs') async def who_is(self, query, session_id='general'): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return random.choice(_confused) + query temp_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chatbotTemplate', 'chatbottemplate.template') chat = Chat(temp_file_path) @commands.Cog.listener() async def on_message(self, message): if message not in _chatbotai_channel_id: return if message.author.bot: return msg = message.content.lower().replace('*', '').replace(',', ' ').replace('.', ' ').replace('_', ' ').replace(' ', '') # author message content now in lowercase and clean if msg.startswith('ok bot '): result = chat.respond(msg) if (len(result) <= 2048): await message.channel.send(result) else: cropped = result[:2000] await message.channel.send(f'{cropped}...')
def c(x): chat = Chat(pairs, reflections) return chat.converse(x)
from chatbot import Chat, register_call import wikipedia @register_call("whoIs") def who_is(query, session_id="general"): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return "I don't know about " + query first_question = "Hi, how are you?" Chat("examples/Example.template").converse(first_question)
)), (r'(.*)\?', ("Why do you ask that?", "Please consider whether you can answer your own question.", "Perhaps the answer lies within yourself?", "Why don't you tell me?")), (r'quit', ("Thank you for talking with me.", "Good-bye.", "Thank you, that will be $150. Have a good day!")), (r'(.*)', ("Please tell me more.", "Let's change focus a bit... Tell me about your family.", "Can you elaborate on that?", "Why do you say that %1?", "I see.", "Very interesting.", "%1.", "I see. And what does that tell you?", "How does that make you feel?", "How do you feel when you say that?"))) def whoIs(query, sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query call = multiFunctionCall({"whoIs": whoIs}) firstQuestion = "Hi, how are you?" Chat(pairs, reflections, call=call).converse(firstQuestion)
def whoIs(query,sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about "+query call = multiFunctionCall({"whoIs":whoIs}) firstQuestion="Hi, how are you?" chat=Chat("Example.template", reflections,call=call) senderID="1,2,3" chat._startNewSession(senderID) chat.conversation[senderID].append('Say "Hello"') #firstQuestion='Say "Hello"' #chat.converse(firstQuestion,sessionID=senderID) message="" while message!="bye": message=input(">") chat.conversation[senderID].append(message) result = chat.respond(message,sessionID=senderID) chat.conversation[senderID].append(result) print(result)
from chatbot import Chat, register_call import os @register_call("increment_count") def memory_get_set_example(session, query): name=query.strip().lower() # Get memory old_count = session.memory.get(name, '0') new_count = int(old_count) + 1 # Set memory session.memory[name]=str(new_count) return f"count {new_count}" chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)), "get_set_memory_example.template")) chat.converse(""" Memory get and set example Usage: increment <name> show <name> remember <name> is <value> tell me about <name> example: increment mango show mango remember sun is red hot star in our solar system tell me about sun """)
seats = cur.fetchall() # for key in flights.keys(): # if key == fno: # if(flights[key].seats[sno].booked == 0): # flights[key].seats[sno].booked = 1 # print("Succesfully booked") # else: # print("This seat has already been taken") return str(seats[0][0]) call = multiFunctionCall({"showSeats":showSeats, "returnFlights":returnFlights, "getFlightDetails":getFlightDetails, "bookFlight":bookFlight}) chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)),"examples/flightRules.template"), reflections,call=call) chat.converse_http("Hi","") @app.route('/chat', methods = ["POST"]) def hello(): print(request.json) message = request.json['message'] print(message) return chat.converse_http(message),200 def whoIs(query,sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query):
def get_bot_response(): response = request.args.get('msg') temp2 = tempp(response) return str(Chat(temp2).say(response))
def initiate_chat(*arg, **kwargs): try: return MyChat(*arg, **kwargs) except (OperationalError, ProgrammingError): # No DB exist print("No DB exist") return Chat(*arg, **kwargs)
def whoIs(query, sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query call = multiFunctionCall({"whoIs": whoIs}) firstQuestion = "Hi, how are you?" Chat('sentences.text', reflections, call=call).converse(firstQuestion) class LString: def __init__(self): self._total = 0 self._successors = defaultdict(int) def put(self, word): self._successors[word] += 1 self._total += 1 def get_random(self): ran = random.randint(0, self._total - 1) for key, value in self._successors.items(): if ran < value:
def acquire_chatbot(): return Chat("./script.template", default_template='./default.template')
def answer(firstQuestion): return Chat("examples/Example.template", reflections,call=call).converse(firstQuestion)
from chatbot import Chat,reflections,multiFunctionCall import wikipedia,os import warnings warnings.filterwarnings("ignore") def whoIs(query,sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about "+query call = multiFunctionCall({"whoIs":whoIs}) firstQuestion="Hi, how are you?" chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)),"Example.template"), reflections,call=call) chat.converse(firstQuestion) #chat.save_template("test.template")
@app.route("/") def hello(): return jsonify({ 'msg': 'hello', }), 200 @app.route("/a") def helloa(): return jsonify({ 'msg': 'hello world', }), 200 chat = Chat( os.path.join(os.path.dirname(os.path.abspath(__file__)), "Example.template")) @app.route("/Bot", methods=['POST']) def Bot(): try: jsondata = request.get_data().decode("utf-8") jsondata = json.loads(jsondata) first_question = jsondata['msg'] # print(chat.say(first_question,jsondata['id'])) return jsonify({ 'msg': chat.say(first_question), "score": sentiment_analyzer_scores(jsondata['msg']) }), 200
import wikipedia import os import warnings warnings.filterwarnings("ignore") @register_call("whoIs") def who_is(query, session_id="general"): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return "I don't know about " + query if __name__ == '__main__': first_question = "" print("test") chat = Chat( os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples/Example.template")) while (first_question != "quit"): code = (input()) first_question = input() print(chat.say(first_question, code))
# https://github.com/ahmadfaizalbh/Chatbot from chatbot import Chat, reflections, multiFunctionCall import wikipedia def whoIs(query, sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query call = multiFunctionCall({"whoIs": whoIs}) firstQuestion = "Hi, how are you?" Chat("pairs.template", reflections, call=call).converse(firstQuestion)
from chatbot import Chat, reflections, multiFunctionCall import wikipedia, os import warnings warnings.filterwarnings("ignore") def whoIs(query, sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query call = multiFunctionCall({"whoIs": whoIs}) firstQuestion = "Hi, how are you? MY name is Gideon an A.I chatbot what can i do for you" chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples/Example.template"), reflections, call=call) chat.converse(firstQuestion)
from flask import Flask from flask import request from flask import jsonify from flask import abort from flask import make_response from datetime import datetime from datetime import timezone import uuid import models as dbHandler from chatbot import Chat, pairs, reflections app = Flask(__name__) chat = Chat(pairs, reflections) @app.route('/talk/bot', methods=['POST']) def getResponse(): if not request: abort(404) query = request.form['query'] response = chat.converse(query) uid = request.form['token'] timeStamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") items = { 'Query': query, 'Response': response, 'UUID': uid, 'Time': timeStamp } dbHandler.insertQueries(uid, timeStamp, query, response) return jsonify({'Items': items})
from chatbot import Chat, reflections, multiFunctionCall import wikipedia def whoIs(query, sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query call = multiFunctionCall({"whoIs": whoIs}) firstQuestion = "Hi, how are you?" Chat("examples/Example.template", reflections, call=call).converse(firstQuestion)
def initiate_chat(*arg,**karg): try:return myChat(*arg,**karg) except (OperationalError,ProgrammingError):#No DB exist print("error") return Chat(*arg,**karg)
def __init__(self, *arg, **karg): super(myChat, self).__init__(*arg, **karg) self._memory = UserSession(UserMemory,self._memory) self.conversation = UserSession(UserConversation,self.conversation) self.topic.topic = UserTopic(self.topic.topic) template_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chatbotTemplate", "Example.template" ) try: chat=myChat(template_file_path) except OperationalError:#No DB exist chat = Chat(template_file_path) def initiate_chat(sender_id): chat.start_new_session(sender_id) chat.conversation[sender_id].append('Say "Hello"') #Get Name of User from facebook url = "https://graph.facebook.com/v2.6/" + sender_id +\ "?fields=first_name,last_name,gender&access_token="+ access_token userInfo=json.load(urllib.urlopen(url)) userInfo["name"] = userInfo["first_name"] chat._memory[sender_id].update(userInfo) def respond_to_client(sender_id,message): recipient = messages.Recipient(recipient_id=sender_id) chat.attr[sender_id]={"match":None,"pmatch":None,"_quote": False} chat.conversation[sender_id].append(message)
from chatbot import Chat, register_call import wikipedia @register_call("whoIs") def who_is(session, query): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return "I don't know about " + query first_question = "Hi, how are you?" Chat("AIbot/Example.template").converse(first_question)
#self._pairs = {'*':[]} #self._reflections = reflections #self._regex = self._compile_reflections() try: chat=myChat(os.path.join(os.path.dirname(os.path.abspath(__file__)), "chatbotTemplate", "Example.template" ), reflections, call=call) except (OperationalError,ProgrammingError):#No DB exist chat = Chat(os.path.join(os.path.dirname(os.path.abspath(__file__)), "chatbotTemplate", "Example.template" ), reflections, call=call) def respond(serviceUrl,channelId,replyToId,fromData, recipientData,message,messageType,conversation): url="https://login.microsoftonline.com/common/oauth2/v2.0/token" data = {"grant_type":"client_credentials", "client_id":app_client_id, "client_secret":app_client_secret, "scope":"https://graph.microsoft.com/.default" } response = requests.post(url,data) resData = response.json() responseURL = serviceUrl + "v3/conversations/%s/activities/%s" % (conversation["id"],replyToId)
from chatbot import Chat, register_call import wikipedia @register_call("whoIs") def who_is(query, session_id="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about " + query chat = Chat("Example.template") sender_id = "1,2,3" chat.start_new_session(sender_id) chat.conversation[sender_id].append('Say "Hello"') message = "" while message != "bye": message = input(">") chat.conversation[sender_id].append(message) result = chat.respond(message, session_id=sender_id) chat.conversation[sender_id].append(result) print(result)
except Exception: return "Internal error, please retry" def service_now(date_str, state, count): if state == "close": state = "closed" date_str = date_str.title() snow_base = "https://vzbuilders.service-now.com/incident_list.do?sysparm_query=" snow_state_urls = { "open": "stateIN1%2C-1%2C2&sysparm_first_row=1", "resolve": "resolved_atON{}@javascript:gs.beginningOf{}()@javascript:gs.endOf{}()", "create": "sys_created_onON{}@javascript:gs.beginningOf{}()@javascript:gs.endOf{}()", "closed": "closed_atON{}@javascript:gs.beginningOf{}()@javascript:gs.endOf{}()", "property": "%5Eu_responsible_property.name={}%5EORcmdb_ci.name={}" } #print(date_str, state, count) url = snow_base + snow_state_urls[state].format(date_str, date_str, date_str) return url first_question = "Hi, how are you?" chat = Chat( os.path.join(os.path.dirname(os.path.abspath(__file__)), "Example.template")) chat.converse(first_question)
from chatterbot.trainers import ChatterBotCorpusTrainer # sample API_ID from https://github.com/telegramdesktop/tdesktop/blob/f98fdeab3fb2ba6f55daf8481595f879729d1b84/Telegram/SourceFiles/config.h#L220 # or use your own api_id = 123456 api_hash = '78a6b613459cb02df7a6ab23f5233bfd' # fill in your own details here phone = '+6585797336' session_file = '@Username' # use your username if unsure password = '******' # if you have two-step verification enabled # content of the automatic reply message = "Sorry, I'll be away until next week!" chat = Chat( "C:/Users/Shearman/Desktop/untitled/venv/Lib/site-packages/chatbot/local/en.template" ) chatbot = ChatBot("shearman") # Create a new trainer for the chatbot trainer = ChatterBotCorpusTrainer(chatbot) # Train based on the english corpus trainer.train("chatterbot.corpus.english") # Train based on english greetings corpus trainer.train("chatterbot.corpus.english.greetings") # Train based on the english conversations corpus trainer.train("chatterbot.corpus.english.conversations")