Beispiel #1
0
def chatbot_train():
    global chatbot
    if chatbot is None:
        chatbot =ChatBot()
    chatbot.retrain_all_bots()
    print('训练成功')
    return json.dumps('训练成功', ensure_ascii=False)
Beispiel #2
0
def chat_with_chatbot():
    handler = ChatBot()
    while 1:
        question = input('用户:')
        print(question)
        answer = handler.chat_answer(question)
        print('小勇:', answer)
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)
Beispiel #4
0
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)
Beispiel #5
0
    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)
Beispiel #6
0
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)
Beispiel #7
0
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 ''
Beispiel #8
0
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])
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))
Beispiel #10
0
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 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
Beispiel #12
0
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')
Beispiel #13
0
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
Beispiel #14
0
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]: ")
Beispiel #15
0
class DialogueManager(object):
    def __init__(self):
        print("Loading resources...")

        self.chatbot = ChatBot()

    def generate_answer(self, question):
        question = utils.text_prepare(question)
        response = self.chatbot.get_response(question)

        return response
Beispiel #16
0
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
Beispiel #17
0
def main():
    """get updates continuosly and manage instructions"""
    last_update_id = None
    chat_bot = ChatBot.chat_bot_start()
    url_handler = UrlHandler()
    bot_manager = BotManager()

    while True:
        print("Updates")
        updates = url_handler.get_updates(last_update_id)

        if updates["result"]:
            last_update_id = url_handler.get_last_update_id(updates) + 1
            bot_manager.handle_updates(updates, chat_bot)

        time.sleep(0.5)
Beispiel #18
0
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, "全血细胞计数能查出啥来")
from chatbot import ChatBot


# Create a new instance of a ChatBot
bot = ChatBot("No Output",
    storage_adapter="chatbot.adapters.storage.JsonDatabaseAdapter",
    logic_adapter="chatbot.adapters.logic.ClosestMatchAdapter",
    io_adapter="chatbot.adapters.io.NoOutputAdapter",
    database="../database.db")

'''
Manipulating the above statement allows you to edit the
configuration to make use of different aspects of the
library. Please see the wiki for in-depth information on
how to configure chatbot.
'''

user_input = "Type something to begin..."

# To make this Python 2.x compatible, replace the print() with print "enter print text here"
print(user_input)

'''
In this example we use a while loop combined with a try-except statement.
This allows us to have a conversation with the chat bot until we press
ctrl-c or ctrl-d on the keyboard.
'''

while True:
    try:
        '''
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

bot = ChatBot("Movie Bot", read_only=False,
        logic_adapters=[
            "chatbot.adapters.logic.AttributeLogicAdapter",
            "chatbot.adapters.logic.TimeLogicAdapter",
            "chatbot.adapters.logic.MovieLogicAdapter",
            "chatbot.adapters.logic.ClosestMatchAdapter"
        ],

        io_adapter="chatbot.adapters.io.NoOutputAdapter",
        database="database_movie.db"
)

response = bot.get_response("")


question = "what movies are playing in Dallas"
print("\n[User]: " + question)
response = bot.get_response(question)
print(response)

question = "recommend a movie for me"
print("[User]: " + question)
response = bot.get_response(question)
print(response)

 def chatbot(self):
     self.new_window = Toplevel(self.root)
     self.app = ChatBot(self.new_window)
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

### START RUNNING WITH
### > sudo mongod

# Create a new instance of a ChatBot
chatbot = ChatBot("Terminal", read_only=True,
    storage_adapter="chatbot.adapters.storage.MongoDatabaseAdapter",
    logic_adapters=[
        "chatbot.adapters.logic.AttributeLogicAdapter",
        "chatbot.adapters.logic.TimeLogicAdapter",
        "chatbot.adapters.logic.WeatherLogicAdapter",
        "chatbot.adapters.logic.MovieLogicAdapter",
        "chatbot.adapters.logic.ClosestMatchAdapter"
    ],
    io_adapter="chatbot.adapters.io.TerminalAdapter",
    pyowm_api_key="cf798079c1e5c638a93cc16cff6d7171",
    #user_profile="user.pkl",
    database="chatterbot-database")

'''
chatbot.train("chatbot.corpus.english.overview")
chatbot.train("chatbot.corpus.english.greetings")
chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.atomic")
chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.atomic-categories0")
chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.knowledge")
chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.ai")
chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.astrology")
Beispiel #23
0
from chatbot import ChatBot
import config

chatbot = ChatBot()

import plugins.public
plugins.public.register(chatbot)

try:
	import plugins.private
	plugins.private.register(chatbot)
except ImportError as exception:
	chatbot.logger.log("ImportError: " + exception.msg)

chatbot.run(config)
Beispiel #24
0
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."
    ])
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

chatbot = ChatBot("HiBot", read_only=False,
    storage_adapter="chatbot.adapters.storage.JsonDatabaseAdapter",
    #storage_adapter="chatbot.adapters.storage.MongoDatabaseAdapter",
    logic_adapters=[
        "chatbot.adapters.logic.AttributeLogicAdapter",
        "chatbot.adapters.logic.EvaluateMathematically",
        "chatbot.adapters.logic.WeatherLogicAdapter",
        "chatbot.adapters.logic.TimeLogicAdapter",
        "chatbot.adapters.logic.ClosestMatchAdapter"
    ],
    pyowm_api_key="cf798079c1e5c638a93cc16cff6d7171",
    database="chaerbot-database_test.db")

# Train based on the english corpus
#chatbot.train("chatterbot.corpus.english")
chatbot.train("chatbot.corpus.english.greetings")
#chatbot.train("chatbot.corpus.english.conversations")
chatbot.train("chatbot.corpus.english.trivia")
#chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.ai")
#chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.drugs")
#chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.sex")
#chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.atomic")
##chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.science")
#chatbot.train("chatbot.corpus.english.AIML.AIML_IN_JSON.misc")

'''
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_())
Beispiel #27
0
import sys
import time

from chatbot import ChatBot


if __name__ == "__main__":

    # create the bot
    qchatbot = ChatBot(False, 'http://real-time-chat.appspot.com/', True)
    
    # navigate to the login page
    qchatbot.visit(qchatbot.site)
    
    # login to the site
    qchatbot.login('aaron', '1234')
    
    # select the friend to talk with
    assert qchatbot.select_friend('alice'), "Your friend is offline"
    
    # quotes to respond with
    quotes, index = [], 0
    with open('quotes.txt', 'rb') as f:
        for line in f:
            quotes.append(line)
    
    # record the nubmer of messages
    num_messages = len(qchatbot.get_messages())
    
    while True:
        # indicates a message was recieved, respond
Beispiel #28
0
def chatbot_start():
    global chatbot
    chatbot =ChatBot()
    chatbot.start_all_bots()
    print('启动成功')
    return json.dumps('启动成功', ensure_ascii=False)
Beispiel #29
0
# 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
Beispiel #30
0
from flask import Flask, request, jsonify
from flask_cors import CORS

from chatbot import ChatBot
from main import init
from utils import get_parser
from utils import MODEL_PATH_MAP

app = Flask(__name__)
CORS(app)
argss = get_parser().parse_args()
# print(argss)
argss.model_name_or_path = MODEL_PATH_MAP[argss.model_type]
init(argss)
chatBot = ChatBot()


@app.route("/api", methods=["GET"])
def api():
    query = request.args.get('query')
    print(query)

    resp = chatBot.main(query)

    return jsonify(query=query,
                   answer=resp[0],
                   doSearch=resp[1],
                   searchQuery=resp[2])


if __name__ == '__main__':
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

chatbot = ChatBot("HiBot", read_only = True,
    storage_adapter="chatbot.adapters.storage.JsonDatabaseAdapter",
    logic_adapters=[
        "chatbot.adapters.logic.EvaluateMathematically",
        "chatbot.adapters.logic.TimeLogicAdapter",
        "chatbot.adapters.logic.ClosestMatchAdapter"
    ])

# Train based on the english corpus
#chatbot.train("chatbot.corpus.english")
chatbot.train("chatbot.corpus.english.greetings")
#chatbot.train("chatbot.corpus.english.conversations")
#chatbot.train("chatbot.corpus.english.trivia")

# Get a response to an input statement
chatbot.get_response("Hello I am a robot....@Qe3")


#chatbot.get_response("What time is it")
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='')
Beispiel #33
0
    if not sys.argv[1]:
      print "Need argument for site to visit (local or app-engine remot)"
      sys.exit()  
  
    if not sys.argv[2]:
      print "Need argument as to which user to login as"
      sys.exit()
    
    if not sys.argv[3]:
      print "Need password of the user to login"
      sys.exit()
      
      
    site = sys.argv[1]
    # create a chatbot instance
    cb1 = ChatBot(True, site, False)
  
      
    # navigate to the chat site
    cb1.visit(sys.argv[1] + '/login')

    # enter the site
    cb1.login(sys.argv[2], sys.argv[3])

    # add a non-existent friend
 #   cb1.add_friend('bob1')

    # select the current freinds list
    friends = cb1.get_friends_list()
    while not friends:
      friends = cb1.get_friends_list()
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

bot = ChatBot("Math & Time Bot", read_only=False,
        logic_adapters=[
            "chatbot.adapters.logic.TimeLogicAdapter",
            "chatbot.adapters.logic.WeatherLogicAdapter",
            "chatbot.adapters.logic.ClosestMatchAdapter"
        ],

        io_adapter="chatbot.adapters.io.NoOutputAdapter",
        pyowm_api_key="cf798079c1e5c638a93cc16cff6d7171",
        database="database_weather.db"
)

response = bot.get_response("")

#response = bot.get_response("whats the weather")
#print("\n"+response)

#response = bot.get_response("what time is it")
#print("\n"+response)

response = bot.get_response("whats the weather in Boston today")
print("\n"+response)

response = bot.get_response("whats the extended weather in Dallas today")
print("\n"+response)
Beispiel #35
0
# -*- 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()
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from chatbot import ChatBot

bot = ChatBot(
    "Math & Time Bot",
    logic_adapters=[
        "chatbot.adapters.logic.EvaluateMathematically",
        "chatbot.adapters.logic.TimeLogicAdapter"
    ],
    io_adapter="chatbot.adapters.io.NoOutputAdapter",
)

# Print an example of getting one math based response
response = bot.get_response("What is 4 + 9?")
print(response)

# Print an example of getting one time based response
response = bot.get_response("What time is it?")
print(response)

# Print an example of getting one time based response
response = bot.get_response("do you know the time")
print(response)

# Print an example of getting one time based response
response = bot.get_response("i had a great time")
print(response)

# Print an example of getting one time based response
Beispiel #37
0
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)
Beispiel #38
0
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 != '':
Beispiel #39
0
import sys
import time

from chatbot import ChatBot


if __name__ == '__main__':

    # create a chatbot instance
    site = 'localhost:8080'
    cb1 = ChatBot(False, site)

    # navigate to the chat site
    cb1.visit(site)

    # enter the site
    cb1.login('asdf', 'asdf')

    # add a non-existent friend
    cb1.add_friend('bob1')

    # select the current freinds list
    friends = cb1.get_friends_list()

    # iterate through the friends list
    for friend in friends:
        # select friend chat window
        cb1.select_friend(friend)
        # send a message
        for i in range(0,5):
            cb1.send_message('qwertyuiopasadfghjklzxcvbnm')
Beispiel #40
0
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)})
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()