def on_new_message(message): current_message = message['data'] #If it is a url, send data to the client if uri_validator(current_message) == True: socketio.emit('url received', {'data': current_message}) info = models.Message(message['data'], name, image) models.db.session.add(info) models.db.session.commit() # if current_message == "!! food": # yelp() #If the message the user writes starts with !!, then call the Chatbot class in chatbot.py elif current_message[:2] == '!!': called_class = chatbot.Chatbot() final_response = called_class.response(current_message) new_message = models.Message(final_response, name, image) models.db.session.add(new_message) models.db.session.commit() else: info = models.Message(message['data'], name, image) models.db.session.add(info) models.db.session.commit() return on_connect()
def handleMessage(data): username = data['Username'] current_message = data['Message'] def is_url(url): try: result = urlparse(url) return all([result.scheme, result.netloc]) except ValueError: return False if current_message[:2] == '!!': username = "******" called_class = chatbot.Chatbot() final_response = called_class.response(current_message) new_message = models.Message("{}: \n {}".format( username, final_response)) models.db.session.add(new_message) models.db.session.commit() #joy working with database table elif current_message[:2] == '!! PR-Music': username = "******" class_call = chatbot.Chatbot() final_response = class_call.response(current_message) new_message = models.Genius("{}: \n {}".format(username, final_response)) models.db.session.add(new_message) models.db.session.commit() elif is_url(current_message) is True: hyperlink_format = '<a href="{link}">{text}</a>' #doesn't work now hyperlink_format.format(link=current_message, text='foo bar') link_text = hyperlink_format.format message_now = models.Message(link_text) models.db.session.add(message_now) models.db.session.commit() else: info = models.Message("{}: \n {}".format(username, data['Message'])) models.db.session.add(info) models.db.session.commit() return on_connect()
def index(request): if request.method == 'POST': form = ArticleForm(request.POST) new_article = form.save() if form.is_valid(): global output output = chatb.listen(new_article.content) if new_article.frontId == '': while (1): myid = random.randint(0, 99) post = Post.objects.filter(iden=myid) if len(post) == 0: break Post.objects.create(iden=myid, content=output[1]) #print(str(myid)+'#'+output[0]) return render(request, 'get.html', { 'form': form, 'data': output[0] }) else: post = Post.objects.filter(iden=new_article.frontId) if len(post) == 0: print('your Id have ERROR!!') return render(request, 'get.html', { 'form': form, 'data': 'your Id have ERROR!!' }) else: if output[0] not in Post.objects.get( iden=new_article.frontId).content.split('#'): Post.objects.filter(iden=new_article.frontId).update( content=output[1]) #print(Post.objects.get(iden=new_article.frontId).content.split('#')) pass return render( request, 'get.html', { 'form': form, 'data': new_article.frontId + '#' + output[0] }) # process.stdin.write(str.encode(new_article.content)) # stdo = process.communicate(input=(new_article.content).encode())[0] # print(process.stdout.readline()) # process.stdout.close() global chatb form = ArticleForm() chatb = chatbot.Chatbot() #process = Popen('python C:/Users/aa/proj_DB/mysite/Chatbot-master/chatbot.py', stdin=PIPE) #for line in iter(process.stdout.readline,''): # print("test:", line.rstrip()) # if line.rstrip() == b'[Console] Initialized successfully :>': # print("I am break") # break #subprocess.Popen('python C:/Users/aa/proj_DB/mysite/Chatbot-master/chatbot.py', stdin=PIPE, stderr=STDOUT,executable=None, shell=False) return render(request, 'create_article.html', {'form': form})
def main(name, dirname, myname): print('Press c to quit interactive mode.') bot = chatbot.Chatbot(dirname=dirname) bot.initialize() while True: line = input(myname + ': ') if line is 'c': sys.exit() words = bot.get_reply(line) words = words.replace('○', myname) words = words.replace('〇', myname) print(name + ': ' + words)
def handleMessage(data): u_message = data['Message'] u2_message = models.Message(data['Message']) #If statement for chatbot here current_message = data['Message'] #If it is a url, send data to the client if current_message[:2] == '!!': called_class = chatbot.Chatbot() final_response = called_class.response(current_message) new_message = models.Message(final_response) models.db.session.add(new_message) models.db.session.commit() else: info = models.Message(data['Message']) models.db.session.add(info) models.db.session.commit() return on_connect()
def main(): args = parse_args() model_name = args.model_name token = args.token if not token: if not "TELEGRAM_TOKEN" in os.environ: print( "Please, set bot token through --token or TELEGRAM_TOKEN env variable" ) return token = os.environ["TELEGRAM_TOKEN"] simple_manager = chatbot.Chatbot(model_name) simple_manager.load_model() bot = BotHandler(token, simple_manager) print("Ready to talk!") offset = 0 while True: updates = bot.get_updates(offset=offset) for update in updates: print("An update received.") if "message" in update: chat_id = update["message"]["chat"]["id"] if "text" in update["message"]: text = update["message"]["text"] if is_unicode(text): print("Update content: {}".format(update)) bot.send_message( chat_id, bot.get_answer(update["message"]["text"])) else: bot.send_message( chat_id, "Hmm, you are sending some weird characters to me..." ) offset = max(offset, update['update_id'] + 1) time.sleep(1)
def main(): bot = chatbot.Chatbot('ice_poseidon') bot.start() # list of bot admins bot_admins = ['your_username', 'your_friends_username'] # Handle incoming messages while True: if bot.has_next_message(): username, message = bot.next_message() print("%s: %s" %(username, message)) # Normie commands if message.lower().startswith('!pyramid'): args = dict(enumerate(message.split(' ')[1:])) try: size = int(args.get(0, 3)) if size > 6: bot.chat('Limit is 6 @{} cmonBruh'.format(username)) elif size > 0: build_pyramid(bot, size) except: print("Failed to make pyramid.") # Admin-only commands if username in bot_admins: # Kill the bot until it is manually restarted if message == '!stop': bot.stop() elif message == '!restart': bot.stop() bot.start() else: # Wait a bit to not over-work the poor bot sleep(0.1)
import argparse import chatbot parser = argparse.ArgumentParser() parser.add_argument('model_name') args = parser.parse_args() model_name = args.model_name bot = chatbot.Chatbot(model_name) bot.load_model() input_raw = ['how are you', 'do you like me', 'what is your hobby', 'do you like football', , 'Hi!', "whats your name?", 'Tell me about yourself' , 'Do you love me?', "What's the meaning of life?", 'How is the weather today?', "Let's have a dinner!" , 'Are you a bot?', 'Why not?'] predictions = bot.get_answer(input_raw) for k, (i, j) in enumerate(zip(input_raw, predictions)): print('%i\n O: %s\n B: %s'%(k, i, j))
from flask import Flask, render_template, request, url_for import pandas as pd import chatbot from difflib import SequenceMatcher app = Flask(__name__) welcome = "Hi! I'm siddharth's Resume Chatbot. How can I help you?" nomatch = "Sorry, I cannot help with that, I will note your question for her reference." qafile = "sid-resume.csv" thankyou = "Thank you for contacting me." exitmessage = "Please type 'bye' to exit the chat." bot = chatbot.Chatbot(nomatch, qafile, thankyou) bot.run_bot() @app.route("/") def home(): return render_template("index.html") @app.route("/resume", methods=['GET']) def resume(): return render_template("resume.html") @app.route("/resume/getresponse") def get_bot_response(): userText = request.args.get('msg') return str(bot.get_response(userText))
import chatbot bot = chatbot.Chatbot() bot.openBrowser() while True: bot.cekAndSendMessage()
def init_chatbot(self, data_path, weights_path): self.chatbot = chatbot.Chatbot() self.chatbot.load_data(data_path) self.chatbot.build_model() self.chatbot.load_weights(weights_path) self.weights_path = weights_path
def setUpClass(cls): cls.bot = chatbot.Chatbot('intents_contextual_chatbot.json')
def index(request): global output if request.method == 'POST': form = ArticleForm(request.POST) new_article = form.save() if form.is_valid(): if new_article.frontId == '': while (1): myid = random.randint(0, 99) post = Post.objects.filter(iden=myid) if len(post) == 0: break #print(output[1]) output = chatb.listen(new_article.content) #output0 = output[0].decode('utf8') if output[1] is not None: Post.objects.create(iden=myid, content=output[1], domain=chatb.root_domain) return HttpResponse( json.dumps({ 'ID': str(myid), 'reply': output[0] })) #return render(request, 'get.html', {'form': form,'data': str(myid)+"#"+output[0]}) #print(str(myid)+'#'+output[0]) else: return HttpResponse(json.dumps({'reply': output[0]})) #return render(request, 'get.html', {'form': form,'data': output[0]}) else: post = Post.objects.filter(iden=new_article.frontId) if len(post) == 0: print('your Id have ERROR!!') return HttpResponse( json.dumps({'reply': 'your Id have ERROR!!'})) #return render(request, 'get.html', {'form': form,'data': 'your Id have ERROR!!'}) else: data = Post.objects.get(iden=new_article.frontId).content chatb.root_domain = Post.objects.get( iden=new_article.frontId).domain output = chatb.listen(new_article.content) temp = list(output[1]) for i in range(0, len(temp), 1): if temp[i] != data[i]: if temp[i] == 't' and data[i] == 'n': data[i] = temp[i] if temp[i] == 'r' and data[i] == 'u': data[i] = temp[i] if temp[i] == 'u' and data[i] == 'l': data[i] = temp[i] if temp[i] == 'e' and data[i] == 'l': data[i] = temp[i] print("".join(data)) print(len(temp)) if output[1] is not None: Post.objects.filter(iden=new_article.frontId).update( content="".join(data)) return HttpResponse( json.dumps({ 'ID': new_article.frontId, 'reply': output[0] })) #return render(request, 'get.html', {'form': form,'data': new_article.frontId+'#'+output[0]}) else: Post.objects.get(iden=new_article.frontId).delete() return HttpResponse( json.dumps({ 'ID': new_article.frontId, 'reply': output[0] })) #return render(request, 'get.html', {'form': form,'data': output[0]}) #print(Post.objects.get(iden=new_article.frontId).content.split('#')) # process.stdin.write(str.encode(new_article.content)) # stdo = process.communicate(input=(new_article.content).encode())[0] # print(process.stdout.readline()) # process.stdout.close() form = ArticleForm() global chatb chatb = chatbot.Chatbot() #process = Popen('python C:/Users/aa/proj_DB/mysite/Chatbot-master/chatbot.py', stdin=PIPE) #for line in iter(process.stdout.readline,''): # print("test:", line.rstrip()) # if line.rstrip() == b'[Console] Initialized successfully :>': # print("I am break") # break #subprocess.Popen('python C:/Users/aa/proj_DB/mysite/Chatbot-master/chatbot.py', stdin=PIPE, stderr=STDOUT,executable=None, shell=False) return render(request, 'create_article.html', {'form': form})
# -*- coding:utf-8 -*- # python2 import sys sys.path.append('../src') import chatbot botman = chatbot.Chatbot() @botman.listen('你好') def hello(): return '你好' if __name__ == "__main__": botman.run()
async def create_cb(chatbot_id, cbs, config): # cbs is the list of chatbots cb = chatbot.Chatbot(id=chatbot_id, cbs=cbs, config=config, loop=loop) await cb._init_plugins() await cb._connect() return cb
# EXAMPLE USAGE import chatbot from time import sleep # Create the bot and kick it off (it runs on another thread) bot = chatbot.Chatbot('ice_poseidon') bot.start() # Handle incoming messages while True: if bot.has_next_message(): username, message = bot.next_message() print("%s: %s" % (username, message)) # commands people can execute if message.lower().startswith('!hello'): bot.chat("Hello @{}!".format(username)) if message.lower().startswith('!bye'): bot.chat("Bye @{}!".format(username)) else: # Wait a bit to not over-work the poor bot sleep(0.1) print("Finished running.")
def create_app(): """ Defines routes and returns a Flask object. """ conf = utils.load_configuration("drwatson.conf") app = flask.Flask(__name__) app.secret_key = os.urandom(128) cors.CORS(app) mongo = pymongo.MongoClient("localhost", 27017) db = mongo.drwatson Watson = w.WatsonConnector(url=conf["watson"]["url"], username=conf["watson"]["username"], password=conf["watson"]["password"], version=conf["watson"]["version"]) Person = p.Personality(url=conf["personality"]["url"], username=conf["personality"]["username"], password=conf["personality"]["password"], version=conf["personality"]["version"]) Chatbot = c.Chatbot(url=conf["chatbot"]["url"], username=conf["chatbot"]["username"], password=conf["chatbot"]["password"], version=conf["chatbot"]["version"], workspace_id=conf["chatbot"]["workspace"]) chatbot_sessions = {} ######### # Feeds # ######### @app.route('/feeds', methods=['GET']) def get_feeds(): """ Returns all available feeds. """ feeds = db.feeds output = [] for s in feeds.find(): output.append(s) return json_util.dumps(output) @app.route('/feeds/<path:feed>', methods=['GET']) def get_feed(feed): """ Returns info for specified feed. """ feed = db.feeds.find({"key": feed}) return json_util.dumps(feed) @app.route('/feeds/<path:key>', methods=['PUT']) def post_feed(key): """ Post new feed """ feeds = db.feeds feed = feeds.find({"key": key}) # TODO: Validate request data key = flask.request.json['key'] url = flask.request.json['url'] name = flask.request.json['name'] active = flask.request.json['active'] date_field = flask.request.json['date_field'] text_field = flask.request.json['text_field'] new_feed = { "key": key, "url": url, "name": name, "active": active, "date_field": date_field, "text_field": text_field } feeds.replace_one({"key": key}, new_feed, True) return flask.jsonify({"result": []}, 201) @app.route('/feeds/<path:key>', methods=['DELETE']) def delete_feed(key): """ Delete a feed. """ feeds = db.feeds feed = feeds.find({"key": key}) if not feed: flask.abort(404) feeds.delete_one({"key": key}) return flask.jsonify({}, 200) ######### # Users # ######### @app.route('/users', methods=['GET']) def get_users(): """ Returns all users. """ users = db.users output = [] for s in users.find(): output.append(s) output = json_util.dumps(output) status = 200 if output == "[]": status = 204 return output, status @app.route('/users/<path:username>', methods=['GET']) def get_user(username): """ Returns Profile for specified user. """ user = db.users.find({"username": username}) user = json_util.dumps(user) status = 200 if user == "[]": status = 204 return user, status @app.route('/users/<path:username>/feeds', methods=['GET']) def get_feeds_for_user(username): """ Returns all feeds for specified user. """ user = db.users.find_one({"username": username}) try: feeds = user["feeds"] status = 200 except IndexError as e: feeds = {} status = 204 feeds = json_util.dumps(feeds) return feeds, status @app.route('/users/<path:username>', methods=['PUT']) def post_user(username): """ Create a new user profile. """ users = db.users # TODO: Validate request data username = flask.request.json['username'] password = flask.request.json['password'] mail = flask.request.json['mail'] feeds = flask.request.json['feeds'] new_user = { "username": username, "mail": mail, "password": password, "feeds": feeds } users.replace_one({"username": username}, new_user, True) return flask.jsonify({}, 201) @app.route('/users/<path:username>', methods=['DELETE']) def delete_user(username): """ Delete a user profile. """ users = db.users user = users.find({"username": username}) if not user: flask.abort(404) users.delete_one({"username": username}) return flask.jsonify({}, 200) ########### # Reports # ########### @app.route('/reports/<path:username>', methods=['GET']) @app.route('/users/<path:username>/reports', methods=['GET']) def get_user_reports(username): """ Returns all reports for specified user. """ reports = db.reports.find({"username": username}) reports = json_util.dumps(reports) status = 200 if reports == "[]": status = 204 return reports, status @app.route('/reports/<path:username>/<path:date>', methods=['GET']) def get_user_report_date(username, date): """ Returns specified report for specified user. """ report = db.reports.find({"username": username, "date": date}) report = json_util.dumps(report) status = 200 if report == "[]": status = 204 return report, status @app.route('/reports/<path:username>/<path:date>', methods=['PUT']) def post_report(username, date): """ Create a new report for a user """ reports = db.reports report = reports.find({"username": username, "date": date}) if not report: flask.abort(404) rm = r.ReportManager(username, Watson, db) rm.ta_report(date) return flask.jsonify({}, 201) @app.route('/reports/<path:username>/<path:date>', methods=['DELETE']) def delete_report(username, date): """ Delete a report """ reports = db.reports report = reports.find({"username": username, "date": date}) if not report: flask.abort(404) reports.delete_one({"username": username, "date": date}) return flask.jsonify({}, 200) @app.route('/pireport/<path:username>', methods=['GET']) def get_user_pireport(username): """ Returns PI report for specified user. """ report = db.pireports.find({"username": username}) report = json_util.dumps(report) status = 200 if report == "[]": status = 204 return report, status ############# # Functions # ############# @app.route('/functions/generate/reports/<path:username>', methods=['GET']) def generate_all_reports(username): """ Generate all reports for specified user. """ rm = r.ReportManager(username=username, watson_manager=Watson, personality=Person, db_connector=db) dates = rm.get_dates() for date in dates: pass #rm.ta_report(date) rm.pi_report() return flask.jsonify({}, 200) @app.route('/functions/chatbot', methods=['POST']) def chatbot(): """ Talk to chatbot. """ # TODO: Validate request data chat_input = flask.request.json['input'] session_id = flask.request.json['sessionid'] if session_id in chatbot_sessions: context = chatbot_sessions[session_id] else: context = {} response = Chatbot.conversate(text=chat_input, context=context) chatbot_sessions[session_id] = response['context'] response_output = response['output'] try: response_output["intent"] = response["intents"] except IndexError as e: response_output["intent"] = [] print(response_output) return flask.jsonify(response_output, 200) return app
#!/usr/bin/env python3 """ Main script. See README.md for more information Use python 3 """ import chatbot import sys if __name__ == "__main__": cb = chatbot.Chatbot() cb.set_up_things() quest = ' '.join(sys.argv[1].split('_')) ans = cb.get_answer(str(quest)) print(ans)