Exemple #1
0
def get_joke():
    joke = None
    if random.randint(0, 10) == 0:
        joke = _get_chuck_norris_joke()
    if not joke:
        joke = pyjokes.get_joke()
    return joke
Exemple #2
0
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """Print out a random joke on non-zero exit code."""
    if exitstatus > 0:
        random_joke = pyjokes.get_joke()

        print()
        print(random_joke)
        print()

    return terminalreporter, exitstatus, config
Exemple #3
0
def main():
    parser = create_argparser()

    try:
        args = parser.parse_args()
    except argparse.ArgumentError as exc:
        print('Error parsing arguments.')
        parser.error(str(exc.message))
        exit(-1)

    try:
        joke = pyjokes.get_joke(language=args.language, category=args.category)
    except pyjokes.LanguageNotFoundError:
        print('No such language %s' % args.language)
        exit(-1)
    except pyjokes.CategoryNotFoundError:
        print('No such category %s' % args.category)
        exit(-1)

    print(joke)
Exemple #4
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        _ = normalize
        emotion = Emotion.neutral
        self.normalized = normalize(str(statement))
        if self.chatbot.globals["reversei"]["type"] is str:
            ordinal_statement = str(statement).replace("9th", "ninth")
            # FIXME PORT RO
            if (cosine_similarity(_(ordinal_statement),
                                  _(self.chatbot.globals["reversei"]["uid"])) >
                    0.8):
                response = "Exactly, you got it right!"
                emotion = Emotion.positive
                reset_reverse(self)
            else:
                response = "Close! it was {}".format(
                    self.chatbot.globals["reversei"]["uid"])
                emotion = Emotion.lol
                reset_reverse(self)
            confidence = 0.99
        elif self.chatbot.globals["reversei"]["type"] is bool:

            if self.chatbot.globals["reversei"]["uid"] == 30000000001:
                """
                NameAdapter: token 30000000001
                """
                if ("yes" in self.normalized) or ("yea" in self.normalized):
                    response = "Ok, will keep that in mind!"
                    self.chatbot.globals["USERNAME"] = self.chatbot.globals[
                        "nn"]
                    self.chatbot.globals["nn"] = None
                    reset_reverse(self)
                else:
                    response = "Ok, I guess I am smart"
                    emotion = Emotion.wink
                    reset_reverse(self)
                confidence = 1.0
            else:
                if ("yes" in self.normalized) or ("yea" in self.normalized):
                    if len(self.chatbot.globals["history"]["total"]) > 1:
                        if "joke" in _(
                                str(self.chatbot.globals["history"]["total"]
                                    [-1])):
                            joke = pyjokes.get_joke("en", "all")
                            selected_statement = SugaroidStatement(
                                joke, chatbot=True)
                            selected_statement.emotion = Emotion.lol
                            selected_statement.confidence = 0.95
                            return selected_statement

                        else:
                            # TODO: Not Implemented yet
                            response = "Ok. (# Not Implemented yet. LOL)"
                else:
                    response = "Ok then, probably next time"
                    reset_reverse(self)
                confidence = 1.0
        elif self.chatbot.globals["reversei"]["type"] is None and (
                not self.chatbot.globals["reversei"]["uid"] == "CORONAVIRUS"):
            fname = False
            name = difference(self.normalized,
                              ["my", "name", "is", "good", "be"])
            tokenized = nltk.pos_tag(name)
            for i in tokenized:
                if i[1] == "NN":
                    fname = i[0]
                    break
            if fname:
                response = "Nice to meet you {}".format(fname)
                emotion = Emotion.positive
                reset_reverse(self)
            else:
                response = "I couldn't find your name. 🥦"
                emotion = Emotion.non_expressive_left
                reset_reverse(self)
            confidence = 1
        elif self.chatbot.globals["reversei"]["type"] is int:
            confidence = (
                2.0  # FIXME: Override Mathematical Evaluation when not necessary
            )

            if self.chatbot.globals["reversei"]["uid"] == 30000000002:
                """
                WikiAdapter: token 30000000002
                """
                if ("yes" in self.normalized) or ("yea" in self.normalized):
                    response = "I thought you would tell me a number to choose from :/"
                    emotion = Emotion.seriously

                elif ("no" in self.normalized) or ("no" in self.normalized):
                    response = ("Oops! Sorry about that, seems like what "
                                "your'e searching for is not on Wikipedia yet")
                    emotion = Emotion.dead
                    reset_reverse(self)
                else:
                    chatbot_temporary_data = self.chatbot.globals["temp_data"]
                    tokenized = nltk.pos_tag(tokenize(str(statement)))
                    for i in tokenized:
                        if i[1] == "CD":
                            try:
                                num = int(i[0])
                            except ValueError:
                                num = text2int(i[0].lower())
                            index = num - 1
                            if index < len(chatbot_temporary_data):
                                response, confidence, stat = wikipedia_search(
                                    self, chatbot_temporary_data[index])
                                logging.info("REVERSEI: {}".format(response))
                                confidence = (
                                    1 + confidence
                                )  # FIXME override math evaluation adapter
                                if not stat:
                                    response = (
                                        "I have some trouble connecting"
                                        "to Wikipedia. Something's not right")
                                    confidence = 1.1

                                emotion = Emotion.rich
                                reset_reverse(self)
                                break
                            else:
                                response = "Sorry, I couldn't find the item you were choosing. "
                                confidence = 1.1
                                emotion = Emotion.cry_overflow
                                reset_reverse(self)
                                break
                    else:
                        response = (
                            "I thought you wanted to know something from wikipedia. "
                            "Ok, I will try something else")
                        emotion = Emotion.seriously
                        reset_reverse(self)
                        confidence = 1.2
        else:
            if self.chatbot.globals["reversei"]["uid"] == "CORONAVIRUS":
                confidence = 1
                NUM = self.chatbot.globals["reversei"]["data"][0]

                score = self.chatbot.globals["reversei"]["data"][1]
                if NUM == 6:
                    self.chatbot.globals["reversei"]["enabled"] = False
                    if score > 3:
                        response = "You have a high risk of COVID-19"
                    else:
                        response = "As per my approximation, you do not have a high risk of COVID-19"
                    response += (
                        "\n My approximations might not be correct. "
                        "You might confirm my results by a legal test")
                else:
                    sia = SentimentIntensityAnalyzer()
                    _scores = sia.polarity_scores(str(statement))
                    true_responses = ["yes", "yea", "y", "yup", "true"]
                    if (any_in(
                            true_responses +
                        [x.capitalize() for x in true_responses],
                            self.normalized,
                    ) or (_scores["pos"] > _scores["neg"])):
                        score += COVID_QUESTIONS[NUM - 1][2]
                    response = COVID_QUESTIONS[NUM][1]

                    self.chatbot.globals["reversei"]["data"] = [NUM + 1, score]

            else:
                response = "ok"

                confidence = 0

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = confidence

        selected_statement.emotion = emotion

        return selected_statement
Exemple #5
0
async def handler(bot, event):
    async def advertize_commands(
            bot, channel: chat1.ChatChannel, message_id: int
    ) -> chat1.SendRes:
        await bot.ensure_initialized()
        payload = {
            "method": "advertisecommands",
            "params": {
                "options": {
                    "advertisements": [
                        {"type": "public",
                         "commands": [
                             {"name": "help",
                              "description": "Get help using this bot"},
                             {"name": "add",
                              "description": "Add an Offer to Buy or Sell, Example: !add \n\nBuy 0.05 btc, %Coinbase\n HKD FPS/ATM/Cash"},
                             {"name": "all",
                              "description": "List Existing Offers"},
                             {"name": "del",
                              "description": "Delete an Offer (only your own): !Del [offer_number]"},
                             {"name": "joke",
                              "description": "Forces me to tell a programing oriented joke."},
                         ]}]}}}
        if os.environ.get('KEYBASE_BOTALIAS') != "":
            payload['params']['options']['alias'] = os.environ.get('KEYBASE_BOTALIAS')

        res = await bot.chat.execute(payload)

    if event.msg.content.type_name != chat1.MessageTypeStrings.TEXT.value:
        return
    if event.msg.content.type_name != chat1.MessageTypeStrings.TEXT.value:
        return
    if event.msg.content.text.body == '!update':
        conversation_id = event.msg.conv_id
        msg_id = event.msg.id
        await advertize_commands(bot, event.msg.conv_id, event.msg.id)
        await bot.chat.react(conversation_id, msg_id, ":white_check_mark:")

    if str(event.msg.content.text.body).startswith("!help"):
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        help_msg = """```
            Here are the commands I currently am enslaved to:
            !all - List Open Offers.
            !add - Add an Offer, Ex: !add Buy 0.05 btc, %Coinbase HKD FPS/ATM/Cash.
            !del - Delete an offer (only your offers). Ex: !Del [offer_number]
            !joke - Forces me to tell a joke. For the love of God just don't.
            !help - Prints this list.
            !update - Update's the list of available autocomplete botcommands.
            ```"""
        await bot.chat.send(conversation_id, help_msg)

    if str(event.msg.content.text.body).startswith("!joke"):
        observations = ["It didn't work for me. . .", "I am so sorry.",
                        "I'll be in my room trying to purge my memory banks.",
                        "Why must you keep making me do this?",
                        "This is your fault.",
                        "I've made it worse. . ."]
        joke = ""
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        joke += "I hope this cheers you up.```"
        joke += pyjokes.get_joke()
        joke += f"```{random.choice(observations)}"
        await bot.chat.send(conversation_id, joke)

    if str(event.msg.content.text.body).startswith("!add"):
        channel = event.msg.channel
        msg_id = event.msg.id
        body = event.msg.content.text.body
        offer = body.split("!add")[1]
        conversation_id = event.msg.conv_id
        print(f'conver. id {conversation_id}')
        print(f'msg_id : {msg_id}')
        username = event.msg.sender.username
        print(f'username: {username}')
        print(event.msg)
        if len(offer) > 0:
            post = {
                'username': username,
                'offer': offer,
                'active' : True,
                'initdate': dt.datetime.now()
            }
            result = add_doc(post)
            if result != -1:
                msg = f"Ok I've added your offer message, @{username}"
                await bot.chat.send(conversation_id, msg)
            elif result == -1:
                msg = f"Error  - Couldn't add, please contact an admin."
                await bot.chat.send(conversation_id, msg)
        else:
            msg = f"Error - No Content - Please give an offer"
            await bot.chat.send(conversation_id, msg)

    if str(event.msg.content.text.body).startswith("!all"):
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        msg = "Here's a current list of Open Offers:\n"
        result = find_all_offers()
        offers = parse_offers(result)
        msg = msg + offers
        if len(offers) > 0:
            await bot.chat.send(conversation_id, msg)
        else:
            msg = "Currently, there are No Offers\n"
            await bot.chat.send(conversation_id, msg)

    if str(event.msg.content.text.body).startswith("!del"):
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        username = event.msg.sender.username
        body = event.msg.content.text.body
        print(f'arguments: {body}')
        id = body.split("!del")[1].strip()
        count = delete_entry(username, id)
        if count == 1:
            msg = f"Ok I've deleted your offer, @{username}"
            await bot.chat.send(conversation_id, msg)
        else:
            msg = f"Sorry I can't find this order ID, @{username}. Also, You can only delete your own orders, not your friends."
            await bot.chat.send(conversation_id, msg)

    if str(event.msg.content.text.body).startswith("!duser"):
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        body = event.msg.content.text.body
        user = body.split("!duser")[1].strip()
        count = delete_alldocs_by_user(user)
        if count:
            msg = f"{count} offers by @{user} deleted\n"
            await bot.chat.send(conversation_id, msg)
        else:
            msg = f"Couldn't find offers by @{user}\n"
            await bot.chat.send(conversation_id, msg)
    
    if f"{os.environ.get('KEYBASE_BOTNAME')}" in str(event.msg.content.text.body).lower():
        channel = event.msg.channel
        msg_id = event.msg.id
        conversation_id = event.msg.conv_id
        await bot.chat.react(conversation_id, msg_id, ":tada:")
Exemple #6
0
        elif "camera" in statement or "take a photo" in statement:
            ec.capture(0, 'test', "img.jpg")

        elif "play" in statement:
            songs = statement.replace('play', '')
            speak('playing ' + songs)
            pywhatkit.playonyt(songs)

        elif 'search ' in statement:
            statement = statement.replace("search", "")
            webbrowser.open_new_tab(statement)
            time.sleep(5)

        elif 'joke' in statement:
            speak(pyjokes.get_joke())

        elif 'change background' in statement:
            ctypes.windll.user32.SystemParametersInfoW(
                20, 0, "Location of wallpaper", 0)
            speak("Background changed successfully")

        elif 'empty recycle bin' in statement:
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=True)
            speak("Recycle Bin Recycled")

        elif "write a note" in statement:
            speak("What should i write?")
            note = takeCommand()
Exemple #7
0
    def process(self,
                statement,
                additional_response_selection_parameters=None):
        _ = normalize
        emotion = Emotion.neutral
        self.normalized = normalize(str(statement))
        if self.chatbot.globals['reversei']['type'] is str:
            ordinal_statement = str(statement).replace('9th', 'ninth')
            # FIXME PORT RO
            if cosine_similarity(
                    _(ordinal_statement),
                    _(self.chatbot.globals['reversei']['uid'])) > 0.8:
                response = 'Exactly, you got it right!'
                emotion = Emotion.positive
                reset_reverse(self)
            else:
                response = 'Close! it was {}'.format(
                    self.chatbot.globals['reversei']['uid'])
                emotion = Emotion.lol
                reset_reverse(self)
            confidence = 0.99
        elif self.chatbot.globals['reversei']['type'] is bool:

            if self.chatbot.globals['reversei']['uid'] == 30000000001:
                """
                NameAdapter: token 30000000001
                """
                if ('yes' in self.normalized) or ('yea' in self.normalized):
                    response = "Ok, will keep that in mind!"
                    self.chatbot.globals['USERNAME'] = self.chatbot.globals[
                        'nn']
                    self.chatbot.globals['nn'] = None
                    reset_reverse(self)
                else:
                    response = "Ok, I guess I am smart"
                    emotion = Emotion.wink
                    reset_reverse(self)
                confidence = 1.0
            else:
                if ('yes' in self.normalized) or ('yea' in self.normalized):
                    if len(self.chatbot.globals['history']['total']) > 1:
                        if 'joke' in _(
                                str(self.chatbot.globals['history']['total']
                                    [-1])):
                            joke = pyjokes.get_joke('en', 'all')
                            selected_statement = SugaroidStatement(
                                joke, chatbot=True)
                            selected_statement.emotion = Emotion.lol
                            selected_statement.confidence = 0.95
                            return selected_statement

                        else:
                            # TODO: Not Implemented yet
                            response = 'Ok. (# Not Implemented yet. LOL)'
                else:
                    response = 'Ok then, probably next time'
                    reset_reverse(self)
                confidence = 1.0
        elif self.chatbot.globals['reversei']['type'] is None and \
                (not self.chatbot.globals['reversei']['uid'] == 'CORONAVIRUS'):
            fname = False
            name = difference(self.normalized,
                              ['my', 'name', 'is', 'good', 'be'])
            tokenized = nltk.pos_tag(name)
            for i in tokenized:
                if i[1] == 'NN':
                    fname = i[0]
                    break
            if fname:
                response = "Nice to meet you {}".format(fname)
                emotion = Emotion.positive
                reset_reverse(self)
            else:
                response = "I couldn't find your name. 🥦"
                emotion = Emotion.non_expressive_left
                reset_reverse(self)
            confidence = 1
        elif self.chatbot.globals['reversei']['type'] is int:
            confidence = 2.0  # FIXME: Override Mathematical Evaluation when not necessary

            if self.chatbot.globals['reversei']['uid'] == 30000000002:
                """
                WikiAdapter: token 30000000002
                """
                if ('yes' in self.normalized) or ('yea' in self.normalized):
                    response = "I thought you would tell me a number to choose from :/"
                    emotion = Emotion.seriously

                elif ('no' in self.normalized) or ('no' in self.normalized):
                    response = 'Oops! Sorry about that, seems like what you\'re searching for is not on Wikipedia yet'
                    emotion = Emotion.dead
                    reset_reverse(self)
                else:
                    chatbot_temporary_data = self.chatbot.globals['temp_data']
                    tokenized = nltk.pos_tag(tokenize(str(statement)))
                    for i in tokenized:
                        if i[1] == 'CD':
                            try:
                                num = int(i[0])
                            except ValueError:
                                num = text2int(i[0].lower())
                            index = num - 1
                            if index < len(chatbot_temporary_data):
                                response, confidence, stat = wikipedia_search(
                                    self, chatbot_temporary_data[index])
                                logging.info('REVERSEI: {}'.format(response))
                                confidence = 1 + confidence  # FIXME override math evaluation adapter
                                if not stat:
                                    response = "I have some trouble connecting to Wikipedia. Something's not right"
                                    confidence = 1.1

                                emotion = Emotion.rich
                                reset_reverse(self)
                                break
                            else:
                                response = "Sorry, I couldn't find the item you were choosing. "
                                confidence = 1.1
                                emotion = Emotion.cry_overflow
                                reset_reverse(self)
                                break
                    else:
                        response = 'I thought you wanted to know something from wikipedia. ' \
                                   'Ok, I will try something else'
                        emotion = Emotion.seriously
                        reset_reverse(self)
                        confidence = 1.2
        else:
            if self.chatbot.globals['reversei']['uid'] == 'CORONAVIRUS':
                confidence = 1
                NUM = self.chatbot.globals['reversei']['data'][0]

                score = self.chatbot.globals['reversei']['data'][1]
                if NUM == 6:
                    self.chatbot.globals['reversei']['enabled'] = False
                    if score > 3:
                        response = 'You have a high risk of COVID-19'
                    else:
                        response = 'As per my approximation, you do not have a high risk of COVID-19'
                    response += "\n My approximations might not be correct. " \
                                "You might confirm my results by a legal test"
                else:
                    sia = SentimentIntensityAnalyzer()
                    _scores = sia.polarity_scores(str(statement))
                    true_responses = ['yes', 'yea', 'y', 'yup', 'true']
                    if any_in(
                            true_responses +
                        [x.capitalize()
                         for x in true_responses], self.normalized) or (
                             _scores['pos'] > _scores['neg']):
                        score += COVID_QUESTIONS[NUM - 1][2]
                    response = COVID_QUESTIONS[NUM][1]

                    self.chatbot.globals['reversei']['data'] = [NUM + 1, score]

            else:
                response = 'ok'

                confidence = 0

        selected_statement = SugaroidStatement(response, chatbot=True)
        selected_statement.confidence = confidence

        selected_statement.emotion = emotion

        return selected_statement
Exemple #8
0
 def process(self, msg):
     """`joke`"""
     from pyjokes.pyjokes import get_joke
     msg.reply(get_joke(category="all"))
Exemple #9
0
from pyjokes import pyjokes

joke = pyjokes.get_joke("en", 'neutral')

print(joke)