def subscribe_reply(msg): user_id = msg['FromUserName'] if msg['Event'] == 'subscribe': print("receive event: subscribe") return reply_to_user(ChatBot().reply_to_subscribe(user_id), user_id) elif msg['Event'] == 'SCAN': print("receive event: SCAN") return reply_to_user( ChatBot().reply_to_order_pay(user_id, msg['EventKey']), user_id) # elif msg['Event'] == 'CLICK' : # print("receive event: CLICK") # role_id = msg['EventKey'] # USER.set_role(user_id, role_id) # return USER.role_modified_reply(role_id) return ''
def main(): parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="count", default=0) args = parser.parse_args() level = logging.NOTSET if args.verbose >= 1 else logging.WARNING logging.basicConfig(format="[%(levelname)s] %(name)s: %(message)s", level=level) config = read_config() username = config["username"] password = config["password"] site = f'https://{config["wiki"]}.fandom.com/' bot = ChatBot(username, password, site, socketio_logger=args.verbose >= 2) bot.add_plugins( HelpPlugin(), AdminPlugin(), LogPlugin(), SeenPlugin(), TellPlugin(), HelloPlugin(), XOPlugin(), TwitterPlugin(), ) if config.get("youtube"): bot.add_plugin(YouTubePlugin(config["youtube"])) try: bot.start() except ClientError as e: logging.critical(str(e)) sys.exit(1)
def chatbot_train(): global chatbot if chatbot is None: chatbot =ChatBot() chatbot.retrain_all_bots() print('训练成功') return json.dumps('训练成功', ensure_ascii=False)
def main(): # Create the pyHoNBot and log in. configs = load_config() config = configs[0] if config: # Hack to allow pyHoNBot to use the correct home directory. bot.home = os.path.join(os.getcwd(), 'deps', 'pyHoNbot') hon_chat_bot = bot.Bot(config) twitch_chat_bot = ChatBot(hon_chat_bot) twitch_chat_bot.connect() # Spawn a new thread to handle the twitch bot chat commands. command_thread = threading.Thread( target=twitch_chat_bot.handle_commands) command_thread.start() # Spawn a new thread to output the text to file for OBS. obs_file_thread = threading.Thread( target=spotify_api.write_to_OBS_file) obs_file_thread.start() # Run the pyHoNBot which connects to the HoN chat channel. honbot_thread = threading.Thread(target=hon_chat_bot.run) honbot_thread.start() # Create the window to manage controls. create_window(twitch_chat_bot)
def main(): checkpoint_file = os.path.join('checkpoints', '6000_checkpoint.tar') checkpoint = torch.load(checkpoint_file, map_location=torch.device('cpu')) encoder_sd = checkpoint['en'] decoder_sd = checkpoint['de'] encoder_optimizer_sd = checkpoint['en_opt'] decoder_optimizer_sd = checkpoint['de_opt'] embedding_sd = checkpoint['embedding'] chatbot_dict = { 'pretrained_embedding': True, 'pretrained_embedding_file': embedding_sd, 'pretrained_enc_dec': True, 'pretrained_enc_file': encoder_sd, 'pretrained_dec_file': decoder_sd } chatbot = ChatBot(**chatbot_dict) chatbot.dc.vocabulary.__dict__ = checkpoint['voc_dict'] chatbot.encoder.eval() chatbot.decoder.eval() searcher = GreedySearchDecoder(chatbot.encoder, chatbot.decoder) evaluateInput(searcher=searcher, voc=chatbot.dc.vocabulary, chatbot=chatbot) return
def chat_with_chatbot(): handler = ChatBot() while 1: question = input('用户:') print(question) answer = handler.chat_answer(question) print('小勇:', answer)
class bot: s = socket.socket() host = 'localhost' port = 5556 c = socket.socket chatbot = ChatBot('Bot') def __init__(self): self.train() self.s.bind((self.host, self.port)) self.s.listen(10) self.c, addr = self.s.accept() self.c.send(str.encode('Owner is offline..')) self.listen() def train(self): trainer = ListTrainer(self.chatbot) fname = open("conversation.txt", "r").readlines() trainer.train(fname) def listen(self): while True: text = str(self.c.recv(1024)) x = len(text) - 3 txt = text[2:x] resp = str(self.chatbot.get_response(txt)) + "..." self.c.send(str.encode(resp))
def main(): eliza = ChatBot(["dialogue/overheard.json", "dialogue/responses.json"], "categories") print("Enter 'quit' to quit") input_string = input("[User input]: ") while input_string != QUIT: if input_string == RELOAD: eliza = ChatBot("responses.json") print("Bot reloaded.") else: response = eliza.get_response(input_string) print(response) input_string = input("[User input]: ")
def voice_reply(msg): user_id = msg['FromUserName'] content = msg['Recognition'] chatbot = ChatBot() print("receive voice") if not content or content.strip() == '': return reply_to_user(chatbot.reply_to_unknown(user_id)) return reply_to_user(chatbot.reply_to_text(user_id, content), user_id)
def respond_to_messages(driver, mesgs): print("respond_to_messages") chatbot = ChatBot() for msgt in mesgs: msg = msgt[0] username = msgt[2] answer = chatbot.estimate_answer(msg.lower()) print(msg, "---->", answer, " :::::: ", username) WhatsAppBot.send_message(driver, username, answer)
def main(): chat_bot = ChatBot() while True: word_phrase = SpeechWorker.get() #test word_phrase = input() if word_phrase is None: pass else: print(word_phrase) response = chat_bot.run(input=word_phrase) print(response) response_select(response=response[Responses.accurate])
def generate_response(): message = str(request.data.decode("utf-8")) if len(message) == 0: return Response("no u", status=500) # flask accepts an entire message history from the website in a POST request, then # 'simulates' all the user messages being handled by the chatbot, so the chatbot is # 'aware' of all previous messages sent. messages = message.split("~^%!*$*!%^~") cbot = ChatBot() result = None for message in messages: result = cbot.handle_message(message) r = jsonify({"message": message, "response": result}) return r
def main(): topn = 20 data = pd.read_csv(config['eval_path']) questions_sel = data.sample(100)['question'].tolist() ct_bot = ChatBot() topn_question = {'top' + str(i): [] for i in range(topn)} for question in questions_sel: cand_questions = ct_bot.eval(question, topn=topn) for i, qs in enumerate(cand_questions): topn_question['top' + str(i)].append(qs) topn_question['input'] = questions_sel topn_question['model'] = 'bert_match' eval_data = pd.DataFrame(topn_question) eval_data.to_csv('./data/eval_data.csv') print('finished create eval data')
def talk(): values = request.get_json() human_chat = values.get('human_chat') name = values.get('bot_name') if human_chat is None: return "Error: You need to talk to me", 400 if name is None: return "Error: You need to tell me who i am", 400 filepath = "./bots/" + name + "/" + name if not os.path.exists(os.path.dirname(filepath)): return "Error: The name of the bot you specified is not found", 404 bot = ChatBot(name) bot_response = bot.response(human_chat) response = {'name': name, 'message': bot_response} return jsonify(response), 200
def main(): bot = ChatBot(botUser, botPass, server=server, ssl=False) bot.debug = False def onLogin(data): bot.getUsers() bot.getGroups() bot.getChannels() bot.createChannel(CHANNEL_PLAYER) bot.createPrivateChat(CHANNEL_WOLF) removeWolves(bot) bot.client.on('logged_in', onLogin) bot.addPrefixHandler('wolf', makeMeWolf) bot.addPrefixHandler('addall', addall) bot.addPrefixHandler('list', listPlayers) bot.addPrefixHandler('rules', showHelp) bot.addPrefixHandler('help', showHelp) bot.addPrefixHandler('Rules', showHelp) bot.addPrefixHandler('Help', showHelp) bot.addPrefixHandler('Join', addPlayers) bot.addPrefixHandler('join', addPlayers) bot.addPrefixHandler('Go', setup) bot.addPrefixHandler('go', setup) bot.addPrefixHandler('Reset', resetGame) bot.addPrefixHandler('reset', resetGame) bot.addPrefixHandler('Restart', resetGame) bot.addPrefixHandler('restart', resetGame) bot.addPrefixHandler('Bite', killVictim) bot.addPrefixHandler('bite', killVictim) bot.addPrefixHandler('Hang', hangSuspect) bot.addPrefixHandler('hang', hangSuspect) bot.start()
def test_chatbot(): handler = ChatBot() question_chatbot(handler, "失眠的并发症") question_chatbot(handler, "乳腺癌的症状有哪些") question_chatbot(handler, "最近老流鼻涕怎么办?") question_chatbot(handler, "为什么有的人会失眠?") question_chatbot(handler, "失眠有哪些并发症?") question_chatbot(handler, "失眠的人不要吃啥?") question_chatbot(handler, "耳鸣了吃点啥?") question_chatbot(handler, "哪些人最好不好吃蜂蜜?") question_chatbot(handler, "鹅肉有什么好处?") question_chatbot(handler, "肝病要吃啥药?") question_chatbot(handler, "板蓝根颗粒能治啥病?") question_chatbot(handler, "脑膜炎怎么才能查出来?") question_chatbot(handler, "怎样才能预防肾虚?") question_chatbot(handler, "感冒要多久才能好?") question_chatbot(handler, "高血压要怎么治?") question_chatbot(handler, "白血病能治好吗?") question_chatbot(handler, "什么人容易得高血压?") question_chatbot(handler, "糖尿病") question_chatbot(handler, "全血细胞计数能查出啥来")
def start_request(message): username = message['nickname'] print 'start request by ' + username if not ((username in players_in_game) or (username in players_in_lobby)): player = Human(username, request.sid, db) username_to_player[username] = player session_to_username[request.sid] = username if not players_in_lobby: print 'adding ' + username + ' to lobby...' players_in_lobby.append(username) else: # remove first player form lobby opponent_username = players_in_lobby.pop() opponent = username_to_player[opponent_username] if random.choice([True, False]): name, random_bot = random.choice(bot.BOTS) chatbot = ChatBot(name, random_bot.start_session(), random_bot.bot_type(), db) print 'matching ' + opponent.name() + ' with ' + chatbot.name() players_in_game[opponent] = Game(opponent, chatbot, players_in_game) print 'adding ' + username + ' to lobby...' players_in_lobby.append(username) else: print 'matching ' + player.name() + ' with ' + opponent.name() #if random.choice([True, False]): game = Game(player, opponent, players_in_game) #else: # game = Game(opponent, player, players_in_game) players_in_game[player] = game players_in_game[opponent] = game
from time import strftime from chatbot import ChatBot # Load the dictionaries of accounts and rosters # created in scripts xmpp_accounts.py and # xmpp_rosters.py accounts = pickle.load(open('xmpp_accounts.p', 'rb')) rosters = pickle.load(open('xmpp_rosters.p', 'rb')) # Loop through the chat agent accounts to set up # their respective rosters on their individual # chat servers for agent in accounts: try: print(strftime('%H:%M:%S') + ' Logging ' + agent + ' into chat server...', end='') user = ChatBot(agent, accounts[agent]) except Exception as e: print('Unable to create Chatbot:', e) continue # Loop through the contacts and send a # subscription request to each. We are # relying on the auto_authorize and # auto_subscribe options being set in # the ChatBot class to enable a two-way # subscription to be set up with a single # subscription request for contact in rosters[agent]: try: # Contacts also need to be logged in to # allow processing of the subscription request print('\tLogging ' + contact + ' into chat server...', end='')
# coding: utf8 # -*- coding: utf-8 -*- from chatbot import ChatBot Bot = ChatBot('Bot') while True: frase = Bot.escuta() resp = Bot.pensa(frase) Bot.fala(resp) if resp == 'tchau': break
import telegram from telegram.ext import CommandHandler from telegram.ext import Updater from telegram.ext import MessageHandler, Filters import logging import time from chatbot import ChatBot chatbot = ChatBot() AUTH_TOKEN = '1170240889:AAHMoQb2mfowo4E9iIZjjXo4kHglo1dqz3c' telegram_bot = telegram.Bot(token=AUTH_TOKEN) updater = Updater(token=AUTH_TOKEN, use_context=True) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def start(update, context): context.bot.send_message( chat_id=update.effective_chat.id, text= "Hello! I am a Telegram Bot for the Integrated COVID-19 Dashboard. Ask me any queries about the website or about COVID-19." ) start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler)
from chatbot import ChatBot if __name__ == '__main__': bot = ChatBot("train") bot.train()
import sys from PyQt5.QtGui import QGuiApplication, QIcon from PyQt5.QtQml import QQmlApplicationEngine from chatbot import ChatBot app = QGuiApplication(sys.argv) app.setWindowIcon(QIcon("resources/disc_logo.png")) engine = QQmlApplicationEngine() chatbb = ChatBot() engine.rootContext().setContextProperty('chatty', chatbb) engine.load('main.qml') engine.quit.connect(app.quit) sys.exit(app.exec_())
def chatbot_start(): global chatbot chatbot =ChatBot() chatbot.start_all_bots() print('启动成功') return json.dumps('启动成功', ensure_ascii=False)
# -*- coding: utf-8 -*- from chatbot import ChatBot def text_handler(bot, msg): uid = msg['FromUserName'] text = str(msg['Content']) answer = bot.answer(uid, text) return answer.replace("<br />", "\n") if __name__ == "__main__": chatbot = ChatBot("elastic") # comment below to avoid reloading FQA and other data, o.w. you should wait for a while before using the bot. chatbot.reload() service = chatbot.service("wechatmp").set_text_handler(text_handler) try: service.start() except KeyboardInterrupt: service.stop()
def chatbot(self): self.new_window = Toplevel(self.root) self.app = ChatBot(self.new_window)
from flask import Flask, request, render_template, jsonify import os from chatbot import ChatBot from sentiment import Smileys from hard_coded import hard_reply from imagenet import ImageNet from wiki import get_summary chatbot = ChatBot(layers=4, maxlen=20, embedding_size=256, batch_size=128, is_train=True, lr=0.001) smileys = Smileys() UPLOAD_FOLDER = 'uploads/' app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/chat', methods=['POST']) def chat(): response = request.form['msg'] response = response.lower()
def init_log(log_file='log/info.log'): handler = TimedRotatingFileHandler(log_file, when="D", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(handler) return logger logger = init_log() bot = ChatBot() app = Flask(__name__, static_url_path='') ######################################## @app.route('/', methods=['GET', 'POST']) def view(): return render_template('index.html') @app.route('/chat', methods=['GET']) def response(): data = request.args.to_dict() message = data['message'] if message != '':
def main(): parser = argparse.ArgumentParser() parser.add_argument("-experiment_dir", default="experiments/exp_9", type=str, required=False, help="The output data dir") parser.add_argument( "-old_model_dir", default="run_6", type=str, required=False, help="filename of saved model. say None to train new model") parser.add_argument( "-old_model_name", default="model_3000.bin", type=str, required=False, help="filename of saved model. say None to train new model") parser.add_argument( "-save_filename", #default="chatbot_history/history_e9_r6_3700", default="chatbot_history/history_5", type=str, required=False, help="filename of saved model. say None to train new model") # for the beam search parser.add_argument("-beam_size", default=6, type=int, required=False, help="4 the beam search") parser.add_argument("-n_best", default=6, type=int, required=False, help="4 the beam search") parser.add_argument( "-choose_best", default=False, type=bool, required=False, help="weather or not to chose the highest ranked response") # device parser.add_argument("-device", default="cpu", type=str, required=False, help="cuda, cpu") parser.add_argument( "-token", default="773295820:AAFF5_lCi4FdWCLd8YRbBJ9AeH2MzZWhhpw", type=str, required=False, help="token for telegram chatbot") args = parser.parse_args() chatbot = ChatBot(args) chatbot.run()
from flask import Flask from flask import render_template from flask import jsonify from flask import request from chatbot import ChatBot # Setting up flask app = Flask(__name__) bot = ChatBot("chat") # Render the main page @app.route("/") def index(): return render_template("index.html") # Get the response from the chatbot @app.route('/message', methods=['POST']) def reply(): data = request.get_json(force=True) line = data.get("text", "") if len(line) > 0 and line[-1] == '\n': line = line[:-1] if line == '': jsonify({"response": "Pardon?"}) return jsonify({"response": bot.chat(line)})
from chatbot import ChatBot if __name__ == '__main__': chatbot = ChatBot('Tom') chatbot.train([ "Hi, can I help you?", "Sure, I'd like to book a flight to Iceland.", "Your flight has been booked." ])