Ejemplo n.º 1
0
 def __init__(self, bot):
     self.bot = bot
     self.client = CleverBot(user=self.bot.config['cleverbot_api_user'],
                             key=self.bot.config['cleverbot_api_key'],
                             nick="KneeDeepAtron")
     self.cw = CleverWrap(self.bot.config['paid_bot_api_key'])
     self.sentience = False
Ejemplo n.º 2
0
 async def mi(self, ctx, *, args):
     '''No point in doing this, can be made better, but will be like this for the moment'''
     cl_key = self.cleverbot_Key
     cl_load = CleverWrap("{}".format(cl_key))
     cl_resp = cl_load.say("{}".format(args))
     await ctx.send(content=cl_resp)
     cl_load.reset()
Ejemplo n.º 3
0
 def __init__(self, tName, tColor, tVoice, tVoiceRate, tFilter):
     self.mCb = CleverWrap("CCCsrAj9GISCVeMvQqFbE0IFc4w")
     self.mName = tName
     self.mColor = tColor
     self.mVoice = tVoice
     self.mVoiceRate = tVoiceRate
     self.mFilter = tFilter
Ejemplo n.º 4
0
    async def setup_chat_helper(self) -> None:
        chat_token = self.config.cleverbot_api_key

        if chat_token is not None:
            self.chat_bot = CleverWrap(chat_token, self.bot.name)
            self.bot.on_user_message += self.respond_to_message
        else:
            await self.channels.log_warning(
                "Cleverbot token not supplied, BunkBot will be mute :(")
Ejemplo n.º 5
0
 def cleverbot(self, speech):
     self.record_btn_text.set('Waiting for cleverbot response...')
     self.gui.update()
     try:
         self.cw = CleverWrap(open(self.cleverbot_apikey).read())
     except FileNotFoundError:
         print(self.cleverbot_apikey, 'file was not found')
         raise FileNotFoundError
     vastus = self.cw.say(speech)
     return vastus
Ejemplo n.º 6
0
def cleverSpeaks(stmt):

    i = 0
    try:
        cw = CleverWrap(api_keys[i][1])
        spoken = cw.say(stmt)
    except requests.exceptions as e:
        print(e)

    return spoken
Ejemplo n.º 7
0
 async def talk(self, ctx, *, pussy:str):
     """talk to the bot"""
     config = Config()
     api_key = config.cb_api_key
     cw = CleverWrap(api_key)
     themessage = cw.say(pussy)
     result = themessage.encode(encoding='UTF-8')
     try:
         await self.bot.say(str(ctx.message.author) + " >> " + cw.say(result))
     except UnicodeDecodeError:
         await self.bot.say("Error has occured trying to decode the Cleverbot message.")
Ejemplo n.º 8
0
async def on_message(client, message):
    print('[DEBUG: Cleverbot] in on_message')
    if (message.content.startswith(CLEVERBOT_COMMAND)):
        cw = CleverWrap("CC1cx7eaidCi0tvh7RfyC7eoYkA")
        clvrbot_msg_cnt = message.content.split(CLEVERBOT_COMMAND)[1]
        print("[DEBUG: Cleverbot] Calling Cleverbot with " + clvrbot_msg_cnt +
              "...")
        answer = cw.say(clvrbot_msg_cnt)
        print("[DEBUG: Cleverbot] " + answer)
        await client.send_message(destination=message.channel, content=answer)
        #"Hello Human."
        cw.reset()  # resets the conversation ID and conversation state.
Ejemplo n.º 9
0
def chat(name):

    cw = CleverWrap('API_KEY')

    #random greetings to start off the conversation
    greetings = [
        "How are you doing today?", "What's up dude?", "How goes it?",
        "How are you?", "What's on your mind?", "How's it hanging bro?",
        "What's going on my dude?"
    ]

    whats = [
        "What was that?", "Come again?", "Could you repeat that?",
        "I'm having a hard time hearing you.", "Please say that again.",
        "What did you say?"
    ]

    byes = [
        "Good talking with you", "Until next time", "Goodbye",
        "It's been a pleasure", "I enjoyed speaking with you", "So long",
        "See you later"
    ]

    engine = pyttsx3.init()
    engine.setProperty('rate', 150)
    engine.say(greetings[randrange(len(greetings))])
    engine.runAndWait()
    r = sr.Recognizer()
    with sr.Microphone(device_index=7) as source:
        while (1):
            r.adjust_for_ambient_noise(source)
            print("\n************** SPEAK NOW *************\n")
            audio = None
            text = None
            try:
                audio = r.listen(source)
                print("Converting to text")
                text = r.recognize_google(audio)
                text = text.lower()
            except sr.UnknownValueError as e:
                engine.say(whats[randrange(len(whats))])
                engine.runAndWait()
                continue
            print("You said: %s" % text)
            if text == "good night sweet prince" or text == "goodnight sweet prince":
                engine.say("%s %s" % (byes[randrange(len(byes))], name))
                engine.runAndWait()
                break
            print("Thinking of a reply")
            reply = cw.say(text)
            print(reply)
            engine.say(reply)
            engine.runAndWait()
Ejemplo n.º 10
0
 async def setup_chat_helper(self) -> None:
     """
     Upon initialization of the bot, connect to the cleverbot through
     the CleverWrap package if the configuration has been setup with a valid key
     """
     chat_token = self.config.cleverbot_api_key
     
     if chat_token is not None:
         self.chat_bot = CleverWrap(chat_token, self.bot.name)
         self.bot.on_user_message += self.respond_to_message
     else:
         await self.channels.log_warning("Cleverbot token not supplied, BunkBot will be mute :(")
Ejemplo n.º 11
0
def chat(user, message):

    global CW

    try:
        sendmessage("@" + user.name + " " + CW.say(message))
    except:
        sendmessage("Error gathering response. Trying again...")
        try:
            CW = CleverWrap(CLEVERBOT_API_KEY)
            sendmessage("@" + user.name + " " + CW.say(message))
        except:
            sendmessage("Unable to get a response.")
Ejemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     TFMProtocol.__init__(self, *args, **kwargs)
     self.factorylist = kwargs["factorylist"]
     self.username = "******"
     self.password = "******"
     self.player_bot = True
     self.room = "*dizzy bootcamp"
     self.requests = {"tribe_otfm": False, "stafflist": False}
     self.loops = {}
     self.staff_list = {"mods": {}, "mapcrew": {}}
     self.chat_list = {}
     self.td = self.get_tfm_info()
     self.cb = CleverWrap("clever_key")
Ejemplo n.º 13
0
Archivo: fun.py Proyecto: kotx/akari
 def __init__(self, bot):
     self.bot = bot
     self.config = bot.config
     self.client = wolframalpha.Client(bot.config.app_id)
     self.invalid_strings = ["Nobody knows.",
                             "It's a mystery.",
                             "I have no idea.",
                             "No clue, sorry!",
                             "I'm afraid I can't let you do that.",
                             "Maybe another time.",
                             "Ask someone else.",
                             "That is anybody's guess.",
                             "Beats me.",
                             "I haven't the faintest idea."]
     self.cw = CleverWrap(bot.config.cwkey)
Ejemplo n.º 14
0
def intent_talk(robot: cozmo.robot.Robot):
    cb = CleverWrap(CLEVERBOT_API_KEY)
    robot.say_text('What do you want to talk about?').wait_for_completed()

    while True:
        speech = csr.wait_for_speech(robot)

        if csr.loose_matches_any(speech, ['bye', 'goodbye', 'good bye'], 1):
            robot.say_text('Goodbye').wait_for_completed()
            return

        reply = cb.say(speech)
        logger.info('Cleverbot says: %s' % reply)

        robot.say_text(reply).wait_for_completed()
Ejemplo n.º 15
0
 def _init_cleverbot(self, tid):
     with self.cleverbots_lock:
         if tid in self.cleverbots:
             return self.cleverbots[tid]
         cleverbot = CleverWrap(self.cleverbot_token)
         self.cleverbots[tid] = cleverbot
         return cleverbot
Ejemplo n.º 16
0
class Bot:
    def __init__(self, tName, tColor, tVoice, tVoiceRate, tFilter):
        self.mCb = CleverWrap("CCCsrAj9GISCVeMvQqFbE0IFc4w")
        self.mName = tName
        self.mColor = tColor
        self.mVoice = tVoice
        self.mVoiceRate = tVoiceRate
        self.mFilter = tFilter

    def ask(self, tQuestion):
        #tQuestion = self.mFilter.removeUnicode(tQuestion)
        tReply = self.mCb.say(tQuestion)
        tReply = self.mFilter.filter(tReply)
        self.type(tReply)
        self.say(tReply)
        return tReply

    def type(self, tText):
        print Colors.BOLD + self.mColor + self.mName + ": " + Colors.ENDC + self.mColor + tText + Colors.ENDC

    def say(self, tText):
        engine = pyttsx.init()
        rate = engine.getProperty('rate')
        engine.setProperty('rate', rate + self.mVoiceRate)
        voices = engine.getProperty('voices')
        engine.setProperty('voice', self.mVoice)
        engine.say(tText)
        a = engine.runAndWait()
Ejemplo n.º 17
0
def _get_cw_for_chat(bot, event):
    """initialise/get cleverbot api wrapper"""

    # setting segregate to False makes cleverbot share its memory across non-segregated conversations
    # important: be careful of information leaking from one conversation to another!
    # by default, conversation memory is segregrated by instantiating new cleverwrap interfaces
    segregate = bot.get_config_suboption(event.conv_id, "cleverbot_segregate")
    if segregate is None:
        segregate = True
    if segregate:
        index = event.conv_id
    else:
        index = "shared"

    if index in __cleverbots:
        return __cleverbots[index]
    else:
        # dev: you can define different API keys for different conversations
        api_key = bot.get_config_suboption(event.conv_id, "cleverbot_api_key")
        if not api_key:
            return None
        else:
            cw = CleverWrap(api_key)
            __cleverbots[index] = cw
            logger.debug("created new cw for {}".format(index))
            return cw
Ejemplo n.º 18
0
def cleverbot_reply(message):
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    sentences = tokenizer.tokenize(message)
    sentence = str()
    smallest = 10000
    for s in sentences:
        l = 50 - len(s)
        l *= l
        if smallest > l:
            sentence = s
            smallest = l
            sentence = re.sub('\W', ' ', sentence)
            print("Idenitified sentence")
            print(sentence)
            # Get CLEVERBOT reply
    cw = CleverWrap("CC1mmFptGklBB3wFbRtjhqGw7AA")
    print("Req : " + sentence)
    reply = (cw.say(sentence))
    return reply
Ejemplo n.º 19
0
    def initialize(self):
        #self.parser = IntentParser(self.emitter)
        self.register_fallback(self.handle_fallback, 90)
        off_intent = IntentBuilder("CleverbotOffIntent"). \
            require("StopKeyword").require("CleverbotKeyword").build()
        on_intent = IntentBuilder("CleverbotOnIntent"). \
            require("StartKeyword").require("CleverbotKeyword").build()
        ask_intent = IntentBuilder("askCleverbotIntent"). \
            require("chatbotQuery").build()
        demo_intent = IntentBuilder("CleverbotdemoIntent"). \
            require("ChatBotDemo").require("CleverbotKeyword").build()
        # register intents
        #self.register_intent(off_intent, self.handle_chat_stop_intent)
        #self.register_intent(on_intent, self.handle_chat_start_intent)
        self.register_intent(ask_intent, self.handle_ask_Cleverbot_intent)
        self.register_intent(demo_intent, self.handle_talk_to_Cleverbot_intent)

        if "api_key" not in self.settings:
            self.speak("you need an api key for cleverbot")
            raise AttributeError("No cleverbot api key provided")

        self.cleverbot = CleverWrap(self.settings["api_key"])
Ejemplo n.º 20
0
def test_say(mock_requests):
    mock_requests.add(
        mock_requests.GET,
        'https://www.cleverbot.com/getreply?input=Hello&key=API_KEY&cs=&conversation_id=&wrapper=CleverWrap.py',
        match_querystring=True,
        json={
            'cs': 'AAAABBCCDD',
            'output': 'Hello.',
            'interaction_count': "2",
            'conversation_id': "foobar",
            'time_taken': "15",
            'time_elapsed': "13",
        },
    )
    cw = CleverWrap("API_KEY")

    assert cw.say("Hello") == "Hello."

    assert cw.default_conversation.convo_id

    cw.reset()

    assert not cw.default_conversation.convo_id
Ejemplo n.º 21
0
class Clever(object):
    def __init__(self, client: commands.Bot):
        self.clever = CleverWrap(basewrapper.Base().get_config_vars("CLEVER"))
        self.client = client
        client.clever_response = self.clever_response

    async def clever_response(self, message):
        response = self.clever.say(message)
        msg = response
        self.clever.reset()
        return msg

    @commands.command(pass_context=True)
    async def clever(self, ctx: commands.Context, *, message: str):
        await self.client.send_typing(ctx.message.channel)
        response = await self.clever_response(message)
        await self.client.say(f"{ctx.message.author.mention} {response}")

    @commands.command(pass_context=True)
    async def convo(self, ctx: commands.Context, *, msg: str):
        await self.client.send_typing(ctx.message.channel)
        response = await self.clever_response(message)
        await self.client.say(f"{ctx.message.author.mention} {response}")
Ejemplo n.º 22
0
def connect_to_cleverbot():
    """
    Connect to the Cleverbot API.

    Returns:
        CleverWrap: The connection to the Cleverbot API
    """

    if CLEVERBOT_API_KEY_VAR in os.environ:
        return CleverWrap(os.environ[CLEVERBOT_API_KEY_VAR])
    raise EnvironmentError(
        "\n\nNo cleverbot API key found. Please do the following to get up and running:"
        "\n- Register a user at 'https://www.cleverbot.com/api/'"
        "\n- Set the environment variable '{}' to the API key value given on your cleverbot api account page."
        .format(CLEVERBOT_API_KEY_VAR))
Ejemplo n.º 23
0
def getTokens():
    config = configparser.ConfigParser()
    if not os.path.isfile("tokens.cfg"):
        print("tokens file missing. ")
        print("Creating one now.")
        config.add_section("Tokens")
        config.set("Tokens", "Bot", "null")
        config.set("Tokens", "Cleverbot", "null")
        with open('tokens.cfg', 'w') as configfile:
            config.write(configfile)
        print("File created.")
        print("Please edit tokens.cfg and then restart.")
        _ = input()
    else:
        config.read('tokens.cfg')
        global botToken
        botToken = config.get('Tokens', 'Bot')
        global cb
        cb = CleverWrap(config.get('Tokens', 'Cleverbot'))
Ejemplo n.º 24
0
from sqlalchemy import create_engine
from json import dumps
from flask.ext.jsonpify import jsonify

import apiai
import speech_recognition as sr
from cleverwrap import CleverWrap
import core as C

import modules as M

CLIENT_ACCESS_TOKEN = '0be9930a8de146deb3014346c5de1d9d'
#Instanciar API.AI
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
#Instanciar Cleverbot
cw = CleverWrap("CC1yyLsWicOuwBwEhMJigtOkixg")

AL = M.Analyzer()

app = Flask(__name__)
api = Api(app)

TOKENS = ['234234123123eddjhskdasa342', '1233543jkk4hkjdhsfhsas']


def APIAI_rec(texto):
    request = ai.text_request()
    request.lang = 'es'  # Lenguaje
    request.session_id = "_HOlaMundo_"
    request.query = texto
    response = request.getresponse()
Ejemplo n.º 25
0
def call_clever_bot(message, clever_bot_convo):
    #url_params = {'input' : message, 'key' : CLEVERBOT_TOKEN}
    try:
        reply = clever_bot_convo.say(message)
        return reply
    except cleverbot.APIError as e:
        print(e.error, e.status)


#main gatta be on the bottom. Code runs top to bottom. Functions need to be init'd first. For future notice (because Joey forgets things).
#------------------------------------------------------#
#Function: main
#Use: main processing of script
#Arguments: none
#Return: none
#------------------------------------------------------#
if __name__ == '__main__':
    slack_client = SlackClient(SLACK_TOKEN)
    cb = CleverWrap(CLEVERBOT_TOKEN)
    convo = cb.conversation()
    if (slack_client.rtm_connect()):
        print("Marvin has connected sir. As if it matters.")
        marvin_id = slack_client.api_call("auth.test")["user_id"]
        while True:
            command, channel = parse_command(slack_client.rtm_read())
            if command:
                handle_command(command, channel, convo)
            time.sleep(READ_WEB_DELAY)
    else:
        print("RTM connection failure. Check Token dingleberry. DO IT AGAIN!")
Ejemplo n.º 26
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
from cleverwrap import CleverWrap
cw = CleverWrap("")

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# almacenamiento con sqlite
import datos as dts

import time
import logging

# Enable logging
logging.basicConfig(
    filename='chatbot.log',
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)


def start(bot, update):
    update.message.reply_text("""\
Indico con precisión los mejores momentos para comprar y vender criptomonedas.
Si sigues mis consejos podrás comprar barato y vender caro.\
""")
    time.sleep(6)
    update.message.reply_text("O esa es la intención al menos.")
    time.sleep(2)
    update.message.reply_text("""\
Ejemplo n.º 27
0
 def __init__(self, botName, apiKey):
     print("Initiate Bot {}".format(botName))
     CleverWrap.__init__(self, apiKey, botName)
Ejemplo n.º 28
0
    with open("settings_testing.json", "rb") as f:
        settings = json.load(f)
    bot = commands.Bot(
        command_prefix=["!"])  # testing bot only responds to !-prefixed cmds

else:
    with open("settings.json", "rb") as f:
        settings = json.load(f)
    bot = commands.Bot(command_prefix=prefixes)

bot.buxman = Manager(bot)
bot.settings = settings
# bot.sesh = aiohttp.ClientSession(loop=bot.loop)
# this has been moved to an "async with" statement in the gelbooru cog so that the
# session is created inside an async function
cb = CleverWrap(settings["cleverbot_token"])
bot.last_chat = datetime.datetime.now(
)  # to determine when to reset the cleverbot interaction
bot.cbchannels = settings["cleverbot_channels"]

with open("snektext.json", "r") as f:
    bot.text = json.load(f)


def is_owner(ctx):
    return ctx.message.author.id == bot.settings["owner_id"]


class NickFind():
    """This needs to appear like a compiled regex object with a findall method"""
    @staticmethod
Ejemplo n.º 29
0
class ChatService(Service):
    def __init__(self, bot: BunkBot, database: DatabaseService,
                 users: UserService, channels: ChannelService):
        super().__init__(bot, database)
        self.chat_bot: CleverWrap = None
        self.chats: List[Chat] = []
        self.users: UserService = users
        self.channels: ChannelService = channels
        self.bot.on_initialized += self.setup_chat_helper
        self.config.raise_error_on_bad_config = False
        #DaemonHelper.add(self.randomly_create_conversation, trigger="interval", hours=INTERVAL_FOR_RANDOM_CHAT)

    async def setup_chat_helper(self) -> None:
        chat_token = self.config.cleverbot_api_key

        if chat_token is not None:
            self.chat_bot = CleverWrap(chat_token, self.bot.name)
            self.bot.on_user_message += self.respond_to_message
        else:
            await self.channels.log_warning(
                "Cleverbot token not supplied, BunkBot will be mute :(")

    # check for if the message sent by a user
    # is meant for bunkbot
    async def respond_to_message(self, message: Message) -> None:
        if not message.author.bot:
            if message.content.startswith("!"):
                await self.bot.process_commands(message)
            else:
                user: BunkUser = self.users.get_by_id(message.author.id)
                chat: Chat = next(
                    (c for c in self.chats if c.user.id == user.id
                     and c.channel_id == message.channel.id), None)
                is_bunk_mention: bool = len(
                    message.mentions
                ) > 0 and message.mentions[0].name == self.bot.name
                parsed_chat: list = Chat.parse(message.content)
                bunk_name_index: int = -1

                try:
                    bunk_name_index = parsed_chat.index(self.bot.name_lower)
                except:
                    bunk_name_index = -1

                if is_bunk_mention or bunk_name_index > -1:
                    if chat is None:
                        chat = Chat(user, message)
                        self.chats.append(chat)

                    is_first = bunk_name_index == 0
                    is_last = bunk_name_index == len(parsed_chat) - 1
                    is_one_time_response = not is_first and not is_last
                    will_respond: bool = True

                    if is_one_time_response:
                        will_respond = randint(0, 100) >= 50

                    if will_respond:
                        await self.respond(chat, message, user)
                        if is_one_time_response:
                            chat.last_message_at = -1
                            self.chats.remove(chat)
                else:
                    if chat is not None and chat.channel_id == message.channel.id:
                        if chat.is_active:
                            if message.content.lower() == "quiet":
                                chat.last_message_at = -1
                                self.chats.remove(chat)
                                await message.channel.send(
                                    ":face_with_hand_over_mouth:")
                            else:
                                await self.respond(chat, message, user)
                        else:
                            self.chats.remove(chat)
                    else:
                        await self.bot.process_commands(message)

    async def respond(self, chat: Chat, message: Message,
                      user: BunkUser) -> None:
        try:
            await message.channel.trigger_typing()
            content: str = self.override(message)

            response: str = self.chat_bot.say(chat.reply(content, user))
            response = self.alter_response(user, response)

            self.update_inactive_chats()

            await message.channel.send(response)
        except Exception as e:
            await self.channels.log_error(e, "ChatService")
            await message.channel.send("I'm sorry... I cannot talk right now")

    def alter_response(self, user: BunkUser, response: str) -> str:
        if not response[-1] in punctuation:
            return response

        if len(self.chats) > 1 and will_execute_on_chance(80):
            response = "{0}, {1}{2}".format(response[:-1], user.name,
                                            response[-1])

        return response

    # every 3 hours, random decide to ping someone (with an exclude list)
    # who is online and not gaming
    async def randomly_create_conversation(self) -> None:
        users: List[BunkUser] = []

        for member in self.bot.server.members:
            user: BunkUser = self.users.get_by_id(member.id)

            if user is not None and user.is_online and not user.is_gaming:
                print("SNAG EM {0}".format(user.name))
                users.append(user)

        user: BunkUser = users[randint(0, len(users) - 1)]

    def update_inactive_chats(self) -> None:
        for chat in self.chats:
            if not chat.check_if_active():
                self.chats.remove(chat)

    # "override" commands for bunkbot
    @staticmethod
    def override(msg: Message) -> bool:
        content: str = msg.content.split()[0]
        if content == "!duel":
            return "Duel me you coward!"

        return msg.content
Ejemplo n.º 30
0
# This is a voice-output interface for CleverBot, a chatbot.
# Needs python3, cleverwrap and flite chattyto run
# python should be present in a unix terminal
#
# pip install cleverwrap
# sudo apt-get install flite
#
# Usage:
# python chatBot.py
# then just type after the > prompt
# to leave, type > I'm leaving

from googletrans import Translator
from cleverwrap import CleverWrap
chatBot = CleverWrap("CC6zkRgO9TPlPcz6AO_zLCunNBg")
import subprocess
import sys

shell = True
#chatBot.reset()


def speak(this):
    print('- ' + str(this))
    subprocess.run(['say', str(this)])


speak('I\'m listening')
var_CH = input('> ')
translator = Translator()
var_EN = translator.translate(var_CH, src='zh-tw', dest='en')