async def akinator(self, ctx, mode="NonNSFW", lang="en"):
     aki = akinator.Akinator()
     finalmode = mode.lower()
     if finalmode == "nonnsfw":
         q = aki.start_game(language=str(lang), child_mode=True)
     else:
         q = aki.start_game(child_mode=False, language=str(lang))
Ejemplo n.º 2
0
def main_game(jarvis):
    ''' Handling of the akinator library '''

    aki = akinator.Akinator()
    try:
        q = aki.start_game()
    except (akinator.AkiServerDown, akinator.AkiTechnicalError):
        try:
            q = aki.start_game("en2")  # 2nd server if the 1st is down
        except (akinator.AkiServerDown, akinator.AkiTechnicalError):
            q = aki.start_game("en3")  # 3rd server if the 2nd is down

    # questions loop
    while aki.progression <= 80:
        try:
            a = input(q + "\n")
        except EOFError:
            a = "cantDoThat"
        if a == "b":
            try:
                q = aki.back()
            except akinator.CantGoBackAnyFurther:
                pass
        elif a == "h":
            print_help(jarvis)
        elif a == "q":
            jarvis.say("See you next time !")
            return
        else:
            try:
                q = aki.answer(a)
            except akinator.InvalidAnswerError:
                jarvis.say("answer not understood, type \"h\" for help",
                           Fore.MAGENTA)

    aki.win()

    imageViewerFromCommandLine = {
        'linux': 'xdg-open',
        'win32': 'explorer',
        'darwin': 'open'
    }[sys.platform]  # get an image Viewer
    try:
        subprocess.run([imageViewerFromCommandLine,
                        aki.picture])  # display image of answer
    except Exception:
        pass
    correct = jarvis.input(
        f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?\n\t"
    )
    if correct.lower() == "yes" or correct.lower() == "y":
        jarvis.say("Yay !!! :D", Fore.GREEN)
    else:
        jarvis.say("Oups :(", Fore.GREEN)
Ejemplo n.º 3
0
def akinator_start(message):
    # go to line 23 to understand what is happening below if you got confused
    bot.send_message(
        message.chat.id,
        "You are now in the game!\nFirst consider a character in your mind and obviously don't tell me who you are thinking of becuase that's my job!\nThen i will ask you questions and you should answer with the prepared keyboard!\nEasy right?\nLet's get started!\nAnd one more thing! you can exit the game anywhere you want by typing /exit\nEnjoy!"
    )
    aki_temp = akinator.Akinator()
    q_temp = aki_temp.start_game()
    users.update({message.chat.id: [aki_temp, q_temp]})
    bot.send_message(message.chat.id,
                     users[message.chat.id][1],
                     reply_markup=akinator_keyboard)
Ejemplo n.º 4
0
async def doit(e):
    sta = akinator.Akinator()
    games.update({e.chat_id: {e.id: sta}})
    try:
        m = await e.client.inline_query(asst.me.username,
                                        f"aki_{e.chat_id}_{e.id}")
        await m[0].click(e.chat_id)
    except BotMethodInvalidError:
        return await asst.send_file(
            e.chat_id,
            aki_photo,
            buttons=Button.inline(get_string("aki_2"),
                                  data=f"aki_{e.chat_id}_{e.id}"),
        )
    if e.out:
        await e.delete()
Ejemplo n.º 5
0
def game(from_id, text, time, returning):
    if text.lower() == 'stop':  # deleting the saved game
        storage.delete(AKINATOR_COLLECTION, str(from_id))
        return {"text": "Thank you for playing! If you want to play again just type and send Akinator!",
                "image_url": None, 'win': True}
    if returning:  # resuming the game
        fields = storage.get(AKINATOR_COLLECTION, str(from_id))  # getting saved game
        aki = load(fields)  # creating akinator instance
        if text.lower() in ['back', 'b']:  # we need to go back
            try:
                response = {"text": aki.back(), "image_url": None, 'win': False}
                aki.last_active = time
                storage.update(AKINATOR_COLLECTION, str(from_id), dump(aki))
                return response
            except akinator.exceptions.CantGoBackAnyFurther:
                return {"text": "Cannot go back! If you want to stop send Stop", "image_url": None, 'win': False}
        try:
            response = {"text": aki.answer(text), "image_url": None, 'win': False}  # passing users answer to akinator
        except akinator.exceptions.InvalidAnswerError:
            return {"text": """You put "{}", which is an invalid answer.
                The answer must be one of these:
                    - "yes" OR "y" OR "0" for YES
                    - "no" OR "n" OR "1" for NO
                    - "i" OR "idk" OR "i dont know" OR "i don't know" OR "2" for I DON'T KNOW
                    - "probably" OR "p" OR "3" for PROBABLY
                    - "probably not" OR "pn" OR "4" for PROBABLY NOT
                If you want to stop playing send word Stop.
                """.format(text), 'win': False, "image_url": None}
        #  checking if we are close to make prediction
        if aki.progression >= 90:  # we can make a prediction
            aki.win()
            response = {'text': "It's {} ({})!".format(aki.name, aki.description), 'win': True}
            if aki.picture:
                response['image_url'] = aki.picture
            storage.delete(AKINATOR_COLLECTION, str(from_id))  # deleting document when the game is over
        else:  # we need to save current progression
            aki.last_active = time
            d = dump(aki)
            storage.update(AKINATOR_COLLECTION, str(from_id), d)
    else:  # creating the new game
        aki = akinator.Akinator()
        # starting game and asking user first question
        response = {"text": aki.start_game(), "image_url": None, 'win': False}
        # save current progress
        aki.last_active = time
        storage.add(AKINATOR_COLLECTION, str(from_id), dump(aki))
    return response
Ejemplo n.º 6
0
def load(d):
    """
    Converts dictionary to entity
    :param d: dictionary with fields
    :return: akinator class object
    """
    entity = akinator.Akinator()
    entity.server = d['server']
    entity.step = d['step']
    entity.progression = d['progression']
    entity.question = d['question']
    entity.frontaddr = d['frontaddr']
    entity.uid = d['uid']
    entity.signature = d['signature']
    entity.session = d['session']
    entity.last_active = d['last_active']
    return entity
Ejemplo n.º 7
0
def akinatorus(infos):
    aki = akinator.Akinator()

    q = aki.start_game(language='fr', child_mode=False)
    while aki.progression <= 80:
        say_speech(q, infos)

        query = myspeech()
        a = query.lower()
        print(a)
        if(a == "oui"):
            a = "y"
        if (a == "non"):
            a = "n"
        if (a == "je ne sais pas"):
            a = "i"
        if ( a == "probablement"):
            a = "p"
        if (a == "probablement pas"):
            a = "pn"


        if (a == "stop"):
            say_speech("très bien, au revoir", infos)

            return(1)
        if a == "b":
            try:
                q = aki.back()
            except akinator.CantGoBackAnyFurther:
                pass
        else:
            q = aki.answer(a)
    aki.win()

    correct =(f"la réponse est  {aki.first_guess['name']} ({aki.first_guess['description']})! ai-je raison?\n\t")
    say_speech(correct, infos)

    query = myspeech()
    a = query.lower() + "\n\t"

    if correct.lower() == "oui" or correct.lower() == "y":
        say_speech("Yay\n", infos)
    else:
        say_speech("Oof\n", infos)
Ejemplo n.º 8
0
def quick_game():
    aki = akinator.Akinator()
    q = aki.start_game()
    while aki.progression <= 85:
        a = input(q + "\n\t")
        if a == "b":
            try:
                q = aki.back()
            except akinator.CantGoBackAnyFurther:
                pass
        else:
            q = aki.answer(a)
    aki.win()
    correct = input(f"It's {aki.name} ({aki.description})! Was I correct?\n{aki.picture}\n\t")
    if correct.lower() == "yes" or correct.lower() == "y":
        print("Yay\n")
    else:
        print("Oof\n")
Ejemplo n.º 9
0
async def akinator(ctx):
	await ctx.send("Akinator is here to guess!")

	def check(msg):
		return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower(
		) in ["y", "n", "p", "b"]

	try:
		aki = ak.Akinator()
		q = aki.start_game()
		while aki.progression <= 80:
			await ctx.send(q)
			await ctx.send("Your answer:(y/n/p/b)")
			msg = await client.wait_for("message", check=check)
			if msg.content.lower() == "b":
				try:
					q = aki.back()
				except ak.CantGoBackAnyFurther:
					await ctx.send(e)
					continue
			else:
				try:
					q = aki.answer(msg.content.lower())
				except ak.InvalidAnswerError as e:
					await ctx.send(e)
					continue
		aki.win()
		embed = discord.Embed(color=ctx.author.top_role.colour)
		embed.add_field(name=f"It's {aki.first_guess['name']}", value = aki.first_guess['description'])
		embed.set_image(url=aki.first_guess['absolute_picture_path'])
		embed.set_footer(text="Is it correct?(y/n)")

		await ctx.send(embed=embed)

		correct = await client.wait_for("message", check=check)
		if correct.content.lower() == "y":
			await ctx.send("Yay\n")
		else:
			await ctx.send("GG you won!!\n")
	except Exception as e:
		await ctx.send(e)
Ejemplo n.º 10
0
    async def aki(self, context):
        await context.send("Akinator is here to guess!")

        def check(message):
            return message.author == context.author and message.channel == context.channel and message.content.lower(
            ) in ["y", "n", "p", "b"]

        try:
            aki = ak.Akinator()
            q = aki.start_game()
            while aki.progression <= 80:
                await context.send(q)
                await context.send("Your answer:(y/n/p/b)")
                msg = await self.client.wait_for("message", check=check)
                if msg.content.lower() == "b":
                    try:
                        q = aki.back()
                    except ak.CantGoBackAnyFurther:
                        await context.send(e)
                        continue
                else:
                    try:
                        q = aki.answer(msg.content.lower())
                    except ak.InvalidAnswerError as e:
                        await context.send(e)
                        continue
            aki.win()
            await context.send(
                f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?(y/n)\n"
                f"{aki.first_guess['absolute_picture_path']}\n\t")
            correct = await self.client.wait_for("message", check=check)
            if correct.content.lower() == "y":
                await context.send("Yay\n")
            else:
                await context.send("Oof\n")
        except Exception as e:
            await context.send(e)
Ejemplo n.º 11
0
 def __init__(self, client, reddit):
     self.client = client
     self.trivia = TriviaClient()
     self.aki = akinator.Akinator()
     self.coin = "<:coin:781367758612725780>"
     self.reddit = reddit
Ejemplo n.º 12
0
 def __init__(self, client):
     self.client = client
     self.trivia = TriviaClient()
     self.aki = akinator.Akinator()
Ejemplo n.º 13
0
import sys
import akinator
from src.server import Server

aki = akinator.Akinator()

q = aki.start_game()

server_port = int(sys.argv[1])
server_name = sys.argv[2]

server = Server(server_name, server_port)
server.create_socket()
start_message, client_address = server.listen()
if start_message == 'start':
    while aki.progression <= 80:
        server.send_message(q + '\n\t', client_address)
        a, client_address = server.listen()
        if a == "b":
            try:
                q = aki.back()
            except akinator.CantGoBackAnyFurther:
                pass
        else:
            q = aki.answer(a)
    aki.win()

    server.send_message(
        f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?\n{aki.first_guess['absolute_picture_path']}\n\t",
        client_address)
    correct, client_address = server.listen()
Ejemplo n.º 14
0
    async def akinator(self, ctx):
        intro = discord.Embed(title="Akinator",
                              description="Hello, " + ctx.author.mention +
                              "I am Akinator!!!",
                              color=discord.Colour.blue())
        intro.set_thumbnail(
            url=
            "https://en.akinator.com/bundles/elokencesite/images/akinator.png?v93"
        )
        intro.set_footer(
            text=
            "Think about a real or fictional character. I will try to guess who it is"
        )
        bye = discord.Embed(title="Akinator",
                            description="Bye, " + ctx.author.mention,
                            color=discord.Colour.blue())
        bye.set_footer(text="Akinator left the chat!!")
        bye.set_thumbnail(
            url=
            "https://i.pinimg.com/originals/28/fc/0b/28fc0b88d8ded3bb8f89cb23b3e9aa7b.png"
        )
        await ctx.send(embed=intro)

        def check(msg):
            return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower(
            ) in ["y", "n", "p", "b", "yes", "no", "probably", "idk", "back"]

        try:
            aki = ak.Akinator()
            q = aki.start_game()
            while aki.progression <= 80:
                question = discord.Embed(title="Question",
                                         description=q,
                                         color=discord.Colour.blue())
                ques = [
                    "https://i.imgflip.com/uojn8.jpg",
                    "https://ih1.redbubble.net/image.297680471.0027/flat,750x1000,075,f.u1.jpg"
                ]
                question.set_thumbnail(url=ques[random.randint(0, 1)])
                question.set_footer(text="Your answer:(y/n/p/idk/b)")
                question_sent = await ctx.send(embed=question)
                try:
                    msg = await self.bot.wait_for("message",
                                                  check=check,
                                                  timeout=30)
                except asyncio.TimeoutError:
                    await question_sent.delete()
                    await ctx.send(
                        "Sorry you took too long to respond!(waited for 30sec)"
                    )
                    await ctx.send(embed=bye)
                    return
                await question_sent.delete()
                if msg.content.lower() in ["b", "back"]:
                    try:
                        q = aki.back()
                    except ak.CantGoBackAnyFurther:
                        await ctx.send(e)
                        continue
                else:
                    try:
                        q = aki.answer(msg.content.lower())
                    except ak.InvalidAnswerError as e:
                        await ctx.send(e)
                        continue
            aki.win()
            answer = discord.Embed(title=aki.first_guess['name'],
                                   description=aki.first_guess['description'],
                                   color=discord.Colour.blue())
            answer.set_thumbnail(url=aki.first_guess['absolute_picture_path'])
            answer.set_image(url=aki.first_guess['absolute_picture_path'])
            answer.set_footer(text="Was I correct?(y/n)")
            await ctx.send(embed=answer)
            #await ctx.send(f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?(y/n)\n{aki.first_guess['absolute_picture_path']}\n\t")
            try:
                correct = await self.bot.wait_for("message",
                                                  check=check,
                                                  timeout=30)
            except asyncio.TimeoutError:
                await ctx.send(
                    "Sorry you took too long to respond!(waited for 30sec)")
                await ctx.send(embed=bye)
                return
            if correct.content.lower() == "y":
                yes = discord.Embed(title="Yeah!!!",
                                    color=discord.Colour.blue())
                yes.set_thumbnail(
                    url=
                    "https://i.pinimg.com/originals/ae/aa/d7/aeaad720bd3c42b095c9a6788ac2df9a.png"
                )
                await ctx.send(embed=yes)
            else:
                no = discord.Embed(title="Oh Noooooo!!!",
                                   color=discord.Colour.blue())
                no.set_thumbnail(
                    url=
                    "https://i.pinimg.com/originals/0a/8c/12/0a8c1218eeaadf5cfe90140e32558e64.png"
                )
                await ctx.send(embed=no)
            await ctx.send(embed=bye)
        except Exception as e:
            await ctx.send(e)
Ejemplo n.º 15
0
class akinatorGame():
    aki = akinator.Akinator()
    AkinatorCmd = atri.Akinator['command'] if atri.Akinator['enable'] else []
    hold = False
    end = False

    @staticmethod
    async def process(messagePlain: str, group, member):
        """
        处理游戏进度
        :param messagePlain
        :param group
        :param member
        """
        global a, q
        if messagePlain == "exit":
            akinatorGame.hold = False
            akinatorGame.end = False

        if akinatorGame.end:  # 评价结果
            if messagePlain.lower() == "yes" or messagePlain.lower() == "y":
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain("Yay")
                    ]
                ))
            else:
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain("Oof")
                    ]
                ))
            akinatorGame.end = False
        if akinatorGame.hold and messagePlain in [
            'yes', 'y', '0',
            'no', 'n', '1',
            'i', 'idk', 'i dont know', "i don't know", '2',
            'probably', 'p', '3',
            'probably not', 'pn', '4'
        ]:  # 分支过程中
            a = messagePlain
            if a == "b":
                try:
                    q = akinatorGame.aki.back()
                    await atri.app.sendGroupMessage(group, MessageChain.create(
                        [
                            Plain(q)
                        ]
                    ))
                except akinator.CantGoBackAnyFurther:
                    pass
            else:
                q = akinatorGame.aki.answer(a)
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain(q + "\n\t"),
                        Plain(f"{akinatorGame.aki.progression}%")
                    ]
                ))

            if akinatorGame.aki.progression > 99:  # 给出结果
                akinatorGame.hold = False
                akinatorGame.aki.win()
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain(
                            f"It's {akinatorGame.aki.first_guess['name']} ({akinatorGame.aki.first_guess['description']})! Was I correct?\n"),
                        Image.fromNetworkAddress(akinatorGame.aki.first_guess['absolute_picture_path'])
                    ]
                ))
                akinatorGame.end = True

        if messagePlain in akinatorGame.AkinatorCmd and not akinatorGame.hold:  # start
            akinatorGame.end = False
            akinatorGame.hold = True
            await atri.app.sendGroupMessage(group, MessageChain.create(
                [
                    Plain("Please wait...\n"
                          '''yes or y or 0 for YES
no or n or 1 for NO
i or idk or i dont know or i don't know or 2 for I DON’T KNOW
probably or p or 3 for PROBABLY
probably not or pn or 4 for PROBABLY NOT'''
                          ),
                ]
            ))
            q = akinatorGame.aki.start_game("cn")
            await atri.app.sendGroupMessage(group, MessageChain.create(
                [
                    Plain(q + "\n\t"),
                    Plain(f"{akinatorGame.aki.progression}%")
                ]
            ))
Ejemplo n.º 16
0
async def aki(ctx, *args):
    """.aki - start a akinator game"""
    """akinator bot. Guesses what thing you're thinking of"""
    aki = akinator.Akinator()  #?create akinator object
    question = aki.start_game(
    )  #start the game and store first question in "question" variable
    user_answer = ""
    global users_currently_running
    """
    global aki_state
    if aki_state == False:
        await ctx.send("Akibot is disabled")
        return
    if aki_state == False:
        print("aki state false")
    """
    def parse_answer(answer):
        result = "invalid"  #if function doesn't alter this default value then answer must be invalid
        acceptable_answers = [
            "yes", "no", "y", "n", "idk", "i dont know", "i don't know",
            "probably", "p", "probably not", "pn"
        ]
        convertible_answers = {
            "yes": ["yess", "ye", "yep"],
            "no": ["nope", "nah", "noo"],
            "i dont know":
            ["not sure", "unsure", "don't know", "dont know", "maybe", "m"],
            "probably": ["likely"],
            "probably not": ["unlikely"]
        }
        quit_commands = ["quit", "exit", "q"]
        if answer in acceptable_answers:
            result = answer
        elif answer in quit_commands:
            result = "quit"
        else:
            for t in convertible_answers.items():
                if answer in t[
                        1]:  #looking through each dicts respective list for matching words
                    result = t[
                        0]  #if word matches value then set result as key
        return result

    def check_author(message_author, op_author=ctx):
        return message_author.author == op_author.author

    if ctx.author in users_currently_running:  #check if user is already running aki
        await ctx.send(f"Akinator already running for {ctx.author}")
        return
    users_currently_running.append(
        ctx.author
    )  #add user to list keeping track of who is currently running aki

    while aki.progression <= 80:  #progression tracks how close akinator is to narrowing down the answer
        await ctx.send(
            f"{ctx.author}: {question}"
        )  #print to terminal the <question>, store user input in answer
        answer_count = 0  #set variable to track failed answer attempts
        while (user_answer == "") or (
                user_answer == "invalid"
        ):  # wait for acceptable input. empty string is first iteration. run again if answer is invalid
            try:  #timeout
                user_answer = await client.wait_for('message',
                                                    check=check_author,
                                                    timeout=90)
                user_answer = str(
                    user_answer.content).lower()  #get the message text
                user_answer = parse_answer(user_answer)
                answer_count += 1  # keep tabs on how many answer attempts
            except:
                await ctx.send(
                    f"{ctx.author}: Timed out (90 seconds), game exited.")
                users_currently_running.remove(
                    ctx.author
                )  # exiting, so remove user from currently running list
                return
            if (answer_count >=
                    3) or (user_answer
                           == "quit"):  #if too many answer attempts then quit
                await ctx.send(f"{ctx.author}: Game exited")
                users_currently_running.remove(
                    ctx.author
                )  #exiting, so remove user from currently running list
                return
            if user_answer == "invalid":  #check if parse_answer has flagged the answer as invalid
                await ctx.send(
                    "please use 'yes' 'no' 'maybe' 'probably' 'probably not' \n 'y' 'n' 'm' 'p' 'pn'"
                )
        question = aki.answer(
            user_answer
        )  #feed akinator your answer and redefine "question" as the next question
        user_answer = ""
    aki.win(
    )  #function runs and adds akinators best guess as "name", "description", and "picture" variables accessible in the "aki" class
    await ctx.send(f"{ctx.author}: I know!, It's {aki.name}"
                   )  #akibot sends its deduced guess
    users_currently_running.remove(
        ctx.author
    )  # exiting as end of game, so remove user from currently running list