# https://github.com/Rapptz/discord.py/blob/async/examples/reply.py
# import requests, json

# def checkanswer(q, text):
#     payload = { "ans" : text}
#     target = "http://triviastorm.net/api/checkanswer/%s/" % (q)
#     r = requests.get(target, params=payload)
#     data = r.json()
#     return data['correct']

# print(checkanswer('17444', 'lich king'))

from apiclient import ApiClient

c = ApiClient("test", token="59d6e8551296d27034a65a05c44c82a2ddb0fc05")

# print(c.getq())
# print(c.getq("movies"))

# print(c.checkanswer(5344, "groundhog day"))
# print(c.checkanswer(5344, "ghostbusters"))

# print(c.getanswer(5344))

q = c.askq("test4")
print(q)
print(c.submitanswer(q["id"], "simon pegg", "myusername22"))
print(c.endq())
Beispiel #2
0
class TriviaBot():
    def __init__(self, channel):
        self.channel = channel
        self.current_q = None
        self.last_q = None
        self.qcount = 0
        self.tag = None
        self.api = ApiClient(channel.id)

    async def endq(self, q=None):
        # print("endq")
        if q is None:
            q = self.current_q
        self.last_q = self.current_q
        self.current_q = None
        answers = ";".join(self.api.getanswer(q))
        print(answers)
        await self.channel.send(
            "Time's up! Nobody got the answer! Acceptable answers: **%s**" %
            (answers))
        await self.afterendq()

    async def sendq(self, tag=None):
        # print("sendq")
        try:
            q = self.api.askq(tag)
        except Exception as e:
            print("Failed getting a q with tag %s" % (tag))
            track = traceback.format_exc()
            print(track)
            await self.channel.send(
                "Couldn't retrieve a question. Your parameters might be invalid. If there was a trivia run, it will be terminated."
            )
            self.qcount = 0
            return

        print(q)
        msg = "**Q#%s: %s**" % (q['id'], q['text'])
        self.current_q = q['id']
        self.hint = q['hint']
        em = None
        if len(q['attachment']) > 0:
            em = discord.Embed()
            em.set_image(url=q['attachment'])

        await self.channel.send(msg, embed=em)
        # schedule a task to end this q after some time
        client.loop.create_task(status_task(self, q['id']))

    async def afterendq(self):
        # print("afterendq")
        self.qcount = self.qcount - 1
        if self.qcount > 0:
            await self.channel.send(
                "%d question(s) remaining in this run. Next question!" %
                (self.qcount))
            await self.sendq(self.tag)
        else:
            self.api.endq()

    def format_scores(self, raw_scores):
        scores = []
        for score in raw_scores:
            scores.append("%s : %s" % (score['name'], score['score']))
        return ", ".join(scores)

    async def checkanswer(self, message):
        text = message.content
        sender = message.author.name
        if self.current_q is not None:
            resp = self.api.submitanswer(self.current_q, text, sender)
            if resp['correct']:
                # correct submission ends the currernt_q
                self.last_q = self.current_q
                self.current_q = None
                msg = '{0.author.mention} is correct!'.format(message)
                answers = ";".join(resp['answers'])
                msg = msg + " Acceptable answers: **" + answers + "**"
                await self.channel.send(msg)
                msg = "Current scores: %s" % (self.format_scores(
                    resp['scores']))
                await self.channel.send(msg)
                await self.afterendq()
            # else do nothing on incorrect answer

    async def report(self, message):
        text = message.content
        sender = message.author.name
        qq = None
        tokens = text.split(" ")
        # check if 2nd token is a question id
        if len(tokens) > 1:
            t1 = tokens[1].replace("#", "")
            if is_number(t1):
                qq = t1

        if qq is None:
            # if no id specified, use last_q
            qq = self.last_q

        if qq is not None:
            try:
                resp = self.api.report(qq, text, sender)
                msg = "Report submitted for #{0}, thanks for the feedback!".format(
                    qq)
                await self.channel.send(msg)
            except:
                msg = "Error reporting feedback. You may have provided an invalid id.`"
                await self.channel.send(msg)
        else:
            msg = "You can specify a question to report by passing the question id: `!report 1234 this question is great!`"
            await self.channel.send(msg)

    async def scores(self):
        resp = self.api.scores()
        msg = "Current scores: %s" % (self.format_scores(resp))
        await self.channel.send(msg)