Exemple #1
0
def shownames(bot, member):
    if member.display_name == member.name or basics.truename(
            bot, member) == member.display_name:
        name = basics.truename(bot, member)
    else:
        name = member.display_name
    return f"{basics.useremoji(bot,member)} {name.replace('@','@­')}"
Exemple #2
0
async def replystring(context,string=None,channel=None, silent=False,user=None):
    import modules.basics as basics

    if user==None:
        user = context.message.author

    if (channel == None or channel.id == context.message.channel.id)\
            and user.id in context.bot.disablereplyping:
        silent=True

    tosay = basics.useremoji(context.bot,user)+" "
    if silent:
        tosay += basics.truename(context.bot,user)
    else:
        tosay += user.mention

    if string is not None and string.startswith("asked"):
        tosay += " "
    else:
        tosay += ": "

    if string is not None:
        tosay += string

    return tosay
Exemple #3
0
async def spruce_command(bot, m):
    if isinstance(m.channel, discord.TextChannel):
        ml = m.guild.members
        rl = m.guild.roles

        memberlayers = []
        for u in m.guild.members:
            memberlayers.append({
                "ret": ["!" + str(u.id), u],
                "equals": [[truename(bot, u)], [u.name], [u.display_name],
                           [str(u.id)]]
            })

        rolelayers = []
        for r in m.guild.roles:
            rolelayers.append({
                "ret": ["&" + str(r.id), r],
                "equals": [[str(r.id)], [r.name]]
            })

        for x in re.findall("{[^}]*}", m.content):
            if x in ["CONT"]:
                continue
            s = x[1:-1]
            found = utility.layeredsearch(memberlayers, s)
            if found is None:
                found = utility.layeredsearch(rolelayers, s)

            if found is not None:
                m.content = m.content.replace(x, "<@{}>".format(found[0]), 1)
                if found[0].startswith("!"):
                    m.mentions.append(found[1])
                else:
                    m.role_mentions.append(found[1])
    return m
Exemple #4
0
    async def bans(self, context):
        """Checks who's banned on the server."""
        s = ""
        try:
            l = await context.message.guild.bans()
        except:
            s = "Understandably, I don't have permission to ban people, so I can't see who has already been banned."
            await talking.reply(context, s)
            return

        if len(l) == 0:
            s = "Nobody is banned on this server."
            await talking.say(context, s)
        else:
            lol = [["User", "Reason", "Mention"]]
            print(l)
            for x in l:
                lol.append([
                    basics.truename(self.bot, x.user),
                    "No reason provided" if x.reason is None else x.reason,
                    x.user.mention
                ])
            s = aesthetic.chart(lol, align=["l", "l", "unwrap"])

            s = "The following users are banned from this server:\n\n" + s
            await talking.reply(context, s, disableaes=True)
Exemple #5
0
 async def sue(self, context):
     """Sue somebody.
     
     Modifiers:
     all|list|stats|records : Display stats from previous cases."""
     bot = self.bot
     m = context.message
     
     # Modifiers
     q = basics.contentq(m.content,split=False)
     q, all = basics.subcommands(context, q,["all|list|stats|records"])
     if all != None:
         lines = [["User"] + list(Sue.getstats(bot, m.author).keys())]
         pages = []
         something = False
         n = 0
         #for a in range(8):
         if m.guild.id in bot.suepoints.keys():
             for k,i in bot.suepoints[m.guild.id].items():
                 u = m.guild.get_member(k)
                 if u == None:
                     continue
                 l = []
                 for k,i in Sue.getstats(bot, u).items():
                     l.append(str(i))
                 lines.append([basics.truename(bot, u)] + l)
                 something = True
         if not something:
             await talking.reply(context,"There aren't any stats on this server.")
         else:
             align = ["l"]
             l = aesthetic.chart(lines,linelimit=20,align=["l"] + (["r"] * (len(lines[0])-1)))
             for n,x in enumerate(l):
                 pages.append(f"__**Suing Stats**__ (Page {n+1}/{len(l)})\n{x}")
             rm = PageMessage(bot, validfor=datetime.timedelta(minutes=5), messagecount=1, userids = [m.author.id], pages=pages, context=context)
         return
     
     # Make sure there's a mention
     if len(m.mentions) == 0:
         await talking.reply(context,"You need to specify who you want to sue!")
         return
     
     # Initialize stuff
     if m.guild.id not in bot.suepoints.keys():
         bot.suepoints[m.guild.id] = {}
     for uid in [m.author.id,m.mentions[0].id]:
         if uid not in bot.suepoints[m.guild.id].keys():
             bot.suepoints[m.guild.id][uid] = {}
             for a in ["suer","suee"]:
                 for b in ["win","lose"]:
                     bot.suepoints[m.guild.id][uid][a + b] = 0
     basics.save(self.bot, "suepoints")
                     
     reason = basics.mentionlesscontent(basics.contentq(m.content,split=False))
     if reason == "":
         reason = "(No reason.)"
     
     suemsg = await talking.say(context,"­",nowebhook=True)
     rm = Sue(bot, validfor=datetime.timedelta(minutes=5), messagecount=1, suer=m.author, suee=m.mentions[0], reason=reason, context=context)
 async def specificroll(self):
     u = random.choice(self.l)
     name = basics.truename(self.bot, u.user)
     reason = u.reason if u.reason else "No reason given"
     self.rerolllist.append(aesthetic.hoveremoji(name))
     self.message = await talking.replystring(
         self.context,
         f"asked {basics.spitback(self.q)}, I respond: {u.user.mention} {aesthetic.hoveremoji(reason)}"
     )
Exemple #7
0
        async def SAVETODICT_give(self):
            bot = self.bot
            gifter = self.gifter
            giftee = self.giftee
            value = self.cost

            giftertokens = ot.otedit(self.bot,
                                     gifter,
                                     0,
                                     False,
                                     channel=context.message.channel)
            gifteetokens = ot.otedit(self.bot,
                                     giftee,
                                     0,
                                     False,
                                     channel=context.message.channel)

            ot.otedit(self.bot,
                      gifter,
                      -value,
                      False,
                      channel=context.message.channel)
            ot.otedit(self.bot,
                      giftee,
                      value,
                      False,
                      channel=context.message.channel)

            self.message = "You've given `{}` Obama Token{} to {}.\n\n{}'s Tokens:\n{} ➔ {}\n\n{}'s Tokens:\n{} ➔ {}".format(
                value, ["", "s"][value != 1], basics.truename(bot, giftee),
                basics.truename(bot, gifter), giftertokens,
                round(giftertokens - value, 2), basics.truename(bot, giftee),
                gifteetokens, round(gifteetokens + value, 2))
            await AchievementBrowser.ach_check(bot, gifter,
                                               self.context.message.channel,
                                               "give", {
                                                   "giftee": giftee,
                                                   "value": value
                                               })
Exemple #8
0
    async def collect(self, payload):
        bot = self.bot
        context = self.context
        m = context.message
        u = m.guild.get_member(payload.user_id)
        tokeninfo = f"Spawn Message ID; {context.message.id}"
        if u.bot:
            return

        self.disrespectcount.setdefault(u.id, 0)
        if payload.emoji.is_unicode_emoji(
        ) or payload.emoji.id != 394587421687152640:
            self.disrespectcount[u.id] += 1
            return
        tokeninfo += f"\nDisrespect Count; {self.disrespectcount[u.id]}"
        self.disableinputs = True
        recentspeaker = False

        timestr = '%Y/%m/%d  %I:%M:%S %p'
        uh = datetime.utcnow() - timedelta(seconds=30)
        if m.created_at <= uh and m.author.id != u.id and not m.author.bot:
            recentspeaker = True
            tokeninfo += f"\nRecent Speaker Message ID; {m.id}\nRecent Speaker Message Timestamp; {m.created_at.strftime(timestr)}"
        else:
            async for msg in m.channel.history(limit=60,
                                               oldest_first=False,
                                               before=m):
                recentspeaker = False
                if msg.created_at <= uh:
                    break
                if msg.author.id != u.id and not msg.author.bot:
                    recentspeaker = True
                    tokeninfo += f"\nRecent Speaker Message ID; {m.id}\nRecent Speaker Message Timestamp; {m.created_at.strftime(timestr)}"
                    break
        tokeninfo += f"\nCollected At; {uh.strftime(timestr)}"

        self.bot.dripfeedmonth.setdefault(m.guild.id, "None")
        month = str(datetime.utcnow().strftime("%Y-%m"))
        try:
            dripfeed = self.bot.dripfeedmonth[
                m.guild.id] != month and not self.bot.ach_tracking[m.guild.id][
                    u.id][74][0]
        except:
            dripfeed = self.bot.dripfeedmonth[m.guild.id] != month
        if dripfeed:
            self.bot.dripfeedmonth[m.guild.id] = month
            basics.save(self.bot, "dripfeedmonth")

        tokens = ot.otedit(bot,
                           u,
                           1,
                           True,
                           channel=m.channel,
                           type="gold",
                           extras={
                               "disrespectcount": self.disrespectcount[u.id],
                               "recentspeaker": recentspeaker,
                               "delayed": self.delayed,
                               "dripfeed": dripfeed
                           })
        bot.preresiduecount.setdefault("gold", {})
        bot.preresiduecount["gold"].setdefault(u.id, 5)

        if bot.preresiduecount["gold"][u.id] > 0:
            bot.preresiduecount["gold"][u.id] -= 1
            await talking.say(
                context, "<:obamatoken:349037437827284992> " +
                await talking.replystring(
                    context,
                    "You got an Obama Token! You now have a total of {}. {}\n{} will be shown this message {} before it gets replaced with an Obama Residue."
                    .format(
                        tokens, aesthetic.hoveremoji(tokeninfo.replace(
                            ";", "")), basics.truename(bot, u),
                        ccc.pluralstr("more time",
                                      bot.preresiduecount["gold"][u.id])),
                    user=u))
            basics.save(bot, "preresiduecount")
        else:
            await utility.safelyclear(
                bot, context.message,
                [[utility.get_emoji(bot, "349037437827284992")]]
            )  # Prevents end() from removing the residue

            ObamaResidue(
                bot,
                validfor=timedelta(minutes=60),
                emoji=utility.get_emoji(bot, "653859091331940355"),
                otheremojis=[basics.useremoji(self.bot, u)] +
                utility.reactiontext(str(tokens)),
                info=
                f"{u.mention} got an Obama Token. They now have a total of {tokens}.\n>>> {tokeninfo.replace(';', ':').replace('  ',' ')}",
                context=context)

            await asyncio.sleep(1)  # Prevents end() from removing the residue

        asyncio.ensure_future(self.end())
Exemple #9
0
    async def achievements(self, context):
        """Opens an achievement display menu.

        Mention someone to see their achievements instead.

        Modifiers:
        top|list|high|rank|ranks : Show a scoreboard. """
        bot = self.bot
        m = context.message
        q = basics.contentq(context.message.content, split=False)

        q, top, transfer = basics.subcommands(
            context, q, ["top|list|high|rank|ranks", "transfer"])

        if top != None:
            achievements = AchievementBrowser.getachievements()
            embed = discord.Embed(title="Achievement Scoreboard", type="rich")
            cap = 0
            for x in achievements:
                if x["special"] == False:
                    cap += 1
            raredict = {}
            highdict = {}
            for s in [m.guild.id, "global"]:
                for k in self.bot.ach_tracking[s].keys():
                    u = context.message.guild.get_member(k)
                    if u != None:
                        score = 0
                        icons = ""
                        for n, x in enumerate(achievements):
                            if x["icon"] not in raredict.keys():
                                raredict[x["icon"]] = 0
                            if n in self.bot.ach_tracking[s][k].keys(
                            ) and x["special"] == False:
                                if False not in self.bot.ach_tracking[s][k][n]:
                                    score += 1
                                    icons += x["icon"]
                                    raredict[x["icon"]] += 1
                        highdict.setdefault(u.id, [u, 0, ""])
                        highdict[u.id][1] += score
                        highdict[u.id][2] += icons
            high = list(highdict.values())

            rarelist = []
            for k in raredict.keys():
                rarelist.append([k, raredict[k]])
            rarelist = sorted(rarelist, key=lambda x: x[1])
            # await mf.say(context,str(rarelist))

            high = sorted(high, key=lambda x: x[1])[::-1]
            high = high
            # print(high)
            numbers = "<:bn_1:327896448232325130> <:bn_2:327896448505217037> <:bn_3:327896452363976704> <:bn_4:327896452464508929> <:bn_5:327896454733627403> <:bn_6:327896456369274880> <:bn_7:327896458067968002> <:bn_8:327896459070537728> <:bn_9:327896459292704769> <:bn_10:327896459477385226>".split(
                " ")

            lol = [[
                "User",
                aesthetic.hoveremoji("Bar"), "Progress", "%", "Rarest"
            ]]
            for n, x in enumerate(high):
                lol.append([])
                u = x[0]
                limit = 16
                if len(basics.truename(bot, u)) > limit:
                    lol[-1].append(basics.truename(bot, u)[:limit - 1] + "…")
                else:
                    lol[-1].append(basics.truename(bot, u))

                prog = x[1] / cap
                lol[-1].append(ccc.bar(bot, 1, prog, "mini"))
                lol[-1].append(f"{x[1]}/{cap}")
                lol[-1].append(f"{math.floor(prog * 100)}%")

                rares = ""
                addedrares = 0
                for y in rarelist:
                    if y[0] in x[2]:
                        rares += y[0]
                        addedrares += 1
                    if addedrares == 6:
                        break
                lol[-1].append(rares)

            s = "You don't have any achievements."
            for x in range(0, len(high)):
                if high[x][0] == context.message.author and high[x][1] != 0:
                    s = "You're ranked #{}.".format(x + 1)

            SortableChart(bot,
                          validfor=datetime.timedelta(minutes=5),
                          context=context,
                          lol=lol,
                          align=["l", "l", "unwrap", "l", "l", "unwrap"],
                          addnumbers=True)

            return
        elif transfer != None and context.message.author == bot.rnl:
            tracking = pickle.load((open(
                'C:\\Users\\Zachary\\Desktop\\kkk\\Non-GML\\ButtBot\\epicord-bot-master\\saveach_tracking.txt',
                'rb')))

            count = pickle.load((open(
                'C:\\Users\\Zachary\\Desktop\\kkk\\Non-GML\\ButtBot\\epicord-bot-master\\saveach_tracking_count.txt',
                'rb')))

            achievements = AchievementBrowser.getachievements()

            for u in tracking.keys():
                for n, x in enumerate(tracking[u]):
                    for baseserver in [
                            bot.epicord,
                            bot.get_guild(403747701566734336)
                    ]:
                        server = "global" if achievements[n][
                            "global"] else baseserver.id
                        if baseserver.get_member(int(u)) == None:
                            continue
                        bot.ach_tracking.setdefault(server, {})
                        bot.ach_tracking[server].setdefault(int(u), {})
                        bot.ach_tracking[server][int(u)].setdefault(n, [])
                        edit = bot.ach_tracking[server][int(u)][n]
                        for nn in range(len(achievements[n]["check"])):
                            if len(edit) < nn + 1:
                                edit.append(False)
                            #
                            # print()
                            # print(edit)
                            # print(edit[nn])
                            # print(tracking[u])
                            # print(tracking[u][n])
                            # print(tracking[u][n][nn])
                            # print()
                            edit[nn] = tracking[u][n][nn] or edit[nn]

                            if u in count:
                                if (n, nn) in count[u]:
                                    bot.ach_tracking_count.setdefault(
                                        server, {})
                                    bot.ach_tracking_count[server].setdefault(
                                        int(u), {})
                                    bot.ach_tracking_count[server][int(
                                        u)].setdefault((n, nn), 0)

                                    editc = bot.ach_tracking_count[server][int(
                                        u)]

                                    editc[(n, nn)] = ccc.highest(
                                        [count[u][(n, nn)], editc[(n, nn)]])

            await talking.say(context, "cool")
            basics.save(bot, "ach_tracking")
            basics.save(bot, "ach_tracking_count")
            return
        ####################################THE REAL DEAL!

        AchievementBrowser(bot,
                           validfor=datetime.timedelta(minutes=10),
                           context=context)
Exemple #10
0
    async def cyclecomic(self, context):
        """Cycle comic manager.

        Cyclecomics being comics where, repeatedly, one person adds two panels, and then shows only the newest panel to another person. Then they add two panels and pass on only the last panel, and so on.

        Modifiers:
        new|create|add : Create a new cyclecomic.
        join|enter : Add yourself to a previously created cyclecomic.
        upload|panel|append : Add a panel to a cyclecomic on which it's your turn.
        pass|give : Make it somebody else's turn on a cycleomic on which it's your turn.
        view|show|release|spew|display : Display a completed cyclecomic.
        """
        async def SAVETODICT_give(self):
            await talking.say(
                self.context,
                f"Hey loser. You've been passed this panel ||{self.url} || by {basics.truename(self.bot,context.message.author)} as part of {q}.",
                channel=self.passonto)
            self.bot.cyclecomics[self.q]["turn"] = self.passonto.id
            basics.save(self.bot, "cyclecomics")
            self.message = "Okay, done."

        async def SAVETODICT_upload(self):
            self.bot.cyclecomics[q]["panelurls"].append(self.image)
            self.bot.cyclecomics[q]["panelcreators"].append(
                self.context.message.author.id)
            basics.save(bot, "cyclecomics")
            await talking.reply(
                context,
                f"Okay, {self.image} has been added. I'm saving the URL, not the actual image. I'm also not your mom(unless you want me to be <:blob_wink:423672830316511232>), so I'm not adding a failsafe if you delete the message and thus an attached image. It'll just not show up and you'll lose all your friends."
            )

        async def SAVETODICT_view(self):
            for n, x in enumerate(self.bot.cyclecomics[self.q]["panelurls"]):
                await talking.say(
                    self.context,
                    f"Panel {n+1}, by <@{self.bot.cyclecomics[self.q]['panelcreators'][n]}>.\n{x}"
                )
                await asyncio.sleep(30)

        bot = self.bot
        m = context.message
        q = basics.contentq(m.content, split=False)

        q, new, join, upload, give, view = basics.subcommands(
            context, q, [
                r"new|create|add", r"join|enter", r"upload|panel|append",
                r"pass|give", r"view|show|release|spew|display"
            ])

        refnum = " ".join(q.split(" ")[1:])
        q = q.split(" ")[0]
        qcaps = q
        q = q.lower()

        current = bot.cyclecomics

        if new is not None:
            for k, i in current.items():
                if i["owner"] == m.author.id != bot.rnl.id:
                    await talking.reply(
                        context,
                        "You can only create one cyclecomic at a time per server to prevent spam."
                    )
                    return
            if not q:
                await talking.reply(
                    context,
                    'Add a nickname to this comic, so that it can be identified by something besides an autogenerated number. Like, I dunno. "penis" or "Chris" or something. Six characters max, limited to numbers, letters, and underscores.'
                )
            elif not re.match(r"^\w{1,6}$", q):
                await talking.reply(
                    context,
                    'Six characters max, limited to numbers, letters, and underscores.'
                )
            else:
                if q in current:
                    await talking.reply(
                        context, f"{basics.spitback(qcaps)} is taken already!")
                else:
                    current[q] = {
                        "owner": m.author.id,
                        "turn": m.author.id,
                        "creationtime": str(datetime.datetime.utcnow().date()),
                        "panelurls": [],
                        "panelcreators": [],
                        "users": [m.author.id],
                        "qcaps": qcaps,
                        "server": m.guild.id
                    }
                    await talking.reply(
                        context,
                        f"Okay, {basics.spitback(qcaps)} is now added. People can join using `s!cc [join]{current[q]['qcaps']}`"
                    )
                    basics.save(bot, "cyclecomics")
        elif join is not None:
            if not q:
                await talking.reply(
                    context,
                    "You need to specify which cyclecomic you want to join!")
            elif q not in current:
                await talking.reply(
                    context,
                    f"{basics.spitback(qcaps)} doesn't seem to exist.")
            elif m.author.id in current[q]["users"]:
                await talking.reply(context,
                                    "You're already in this cyclecomic!")
            else:
                current[q]["users"].append(m.author.id)
                basics.save(bot, "cyclecomics")
                await talking.reply(
                    context, "Coolio, you've been added to this cyclecomic.")
        elif upload is not None:
            if not q:
                await talking.reply(
                    context,
                    "You need to specify which cyclecomic you want to add a panel to!"
                )
            elif q not in current:
                await talking.reply(
                    context,
                    f"{basics.spitback(qcaps)} doesn't seem to exist.")
            elif m.author.id not in current[q]["users"]:
                await talking.reply(
                    context,
                    f"You aren't a member of this cyclecomic. You can join with `s!cc [join]{current[q]['qcaps']}`."
                )
            elif current[q]["turn"] != m.author.id:
                await talking.reply(context,
                                    f"It's not your turn on this cyclecomic.")
            else:
                image = await utility.referenceimage(context, returnurl=True)
                if image:
                    ConfirmMessage(
                        bot,
                        validfor=datetime.timedelta(minutes=5),
                        message=
                        f"Are you sure you want to add ||{image} || to {q}?",
                        image=image,
                        q=q,
                        yesscript=SAVETODICT_upload,
                        context=context)
        elif give is not None:
            if not q:
                await talking.reply(
                    context,
                    "You need to specify which cyclecomic you want to pass off on!"
                )
            elif q not in current:
                await talking.reply(
                    context,
                    f"{basics.spitback(qcaps)} doesn't seem to exist.")
            elif m.author.id not in current[q]["users"]:
                await talking.reply(
                    context,
                    f"You aren't a member of this cyclecomic. You can join with `s!cc [join]{current[q]['qcaps']}`."
                )
            elif current[q]["turn"] != m.author.id:
                await talking.reply(context,
                                    f"It's not your turn on this cyclecomic.")
            else:
                try:
                    server = bot.get_guild(current[q]['server'])
                    u = utility.get_member_or_user(
                        bot, server, current[q]['users'][int(refnum)])
                except:
                    await talking.reply(
                        context,
                        f"I couldn't figure out who {basics.spitback(refnum)} referred to. Use s!cc {current[q]['qcaps']} and give me the reference number of the peron you want to pass to."
                    )
                else:
                    if u.id == m.author.id:
                        await talking.reply(
                            context,
                            f"*You're* {basics.truename(bot,u)}, dummy!")
                    else:
                        if current[q]['panelurls']:
                            url = current[q]['panelurls'][-1]
                        else:
                            url = "I lied. I decieved you. Nothing has been added to this cyclecomic yet."
                        ConfirmMessage(
                            bot,
                            validfor=datetime.timedelta(minutes=5),
                            message=
                            f"Are you sure you want to pass ||{url} || to {basics.truename(bot,u)}?",
                            passonto=u,
                            url=url,
                            q=q,
                            yesscript=SAVETODICT_give,
                            context=context)
        elif view is not None:
            if not q:
                await talking.reply(
                    context,
                    "You need to specify which cyclecomic you want to show!")
            elif q not in current:
                await talking.reply(
                    context,
                    f"{basics.spitback(qcaps)} doesn't seem to exist.")
            elif m.author.id != current[q]["owner"]:
                await talking.reply(
                    context,
                    f"You don't own this cyclecomic, so you can't set it off.")
            else:
                ConfirmMessage(
                    bot,
                    validfor=datetime.timedelta(minutes=5),
                    message=
                    f"Are you sure you want to display the entirety of {q}? You can't turn back. It'll be EVERYWHERE.",
                    q=q,
                    yesscript=SAVETODICT_view,
                    context=context)
        else:
            if not q:
                s = "Here's a list of cyclecomics in this server. Specify one to get more info on it.\n`"
                for x in current.keys():
                    s += f"\n{x}"
                s += "`"
                await talking.reply(context, s)
            elif q not in current:
                await talking.reply(
                    context,
                    f"{basics.spitback(qcaps)} isn't a cyclecomic on this server."
                )
            else:
                lol = [["User", "Turn", "Owner", "Panels", "Ref. #", "Status"]]
                for n, x in enumerate(current[q]["users"]):
                    u = utility.get_member_or_user(bot, m.guild, x)
                    lol.append([
                        basics.truename(bot, u), u.id == current[q]["turn"],
                        u.id == current[q]["owner"],
                        current[q]["panelcreators"].count(u.id), n,
                        aesthetic.statusemoji(bot, u)
                    ])
                SortableChart(bot,
                              validfor=datetime.timedelta(minutes=5),
                              context=context,
                              lol=lol,
                              initialsort=[1, 0])
Exemple #11
0
    async def obamaresidue(self, context):
        """Shows how much Obama Residue you have. Mention somebody to check how much they have instead.

        Modifiers:
        all|max|now|top|list : Displays a chart of server-wide residue counts."""
        q = basics.contentq(context.message.content, split=False)
        q, max = basics.subcommands(context, q, [r"all|max|now|top|list"])
        bot = self.bot

        ot.otedit(self.bot,
                  context.message.author,
                  0,
                  False,
                  channel=context.message.channel)
        if max is not None:
            l = [["User", "Max", "Now", "Me", "Mentioned"]]
            for k in self.bot.obamaresidue[context.message.guild.id].keys():
                k = context.message.guild.get_member(k)
                if k is None:
                    continue
                ot.otedit(self.bot,
                          k,
                          0,
                          False,
                          channel=context.message.channel)
                if k != None:
                    l.append([
                        basics.truename(bot, k),
                        round(
                            self.bot.obamaresiduemax[context.message.guild.id][
                                k.id] / 1000, 3),
                        round(
                            self.bot.obamaresidue[context.message.guild.id][
                                k.id] / 1000,
                            3), k.id == context.message.author.id, k
                        in context.message.mentions
                    ])

            SortableChart(bot,
                          lol=l,
                          validfor=timedelta(minutes=5),
                          context=context,
                          initialsort=[4, 1, 2, 3, 5],
                          addnumbers=True,
                          resetnumbers={2, 3},
                          defaultreverse={2, 3, 4, 5})

            return
        target = context.message.author
        if len(context.message.mentions) > 0:
            target = context.message.mentions[0]
            ot.otedit(self.bot,
                      target,
                      0,
                      False,
                      channel=context.message.channel)

        if target == context.message.author:
            targetstr = "You currently have"
            targetstr2 = "Your"
        else:
            targetstr = "{} currently has".format(ccc.shownames(bot, target))
            targetstr2 = "Their"
        await talking.reply(
            context, "{} {} Obama Residue. {} all-time count is {}.".format(
                targetstr,
                round(self.bot.obamaresidue[target.guild.id][target.id] / 1000,
                      3), targetstr2,
                round(
                    self.bot.obamaresiduemax[target.guild.id][target.id] /
                    1000, 3)))
Exemple #12
0
    async def daily(self, context):
        """Opt in or out of free tokens for people you like.

        Once a day, after a random message, you'll be shown three random people and be offered to give a token to one of them.
        Use [list] to see which people have opted in and if they've gotten their token today.
        Use [dm] to toggle getting informed that you recieved a token in DMs rather than the same channel."""
        if context.message.guild.id not in self.bot.sdailylast.keys():
            self.bot.sdailylast[context.message.guild.id] = {}
            basics.save(self.bot, "sdailylast")

        bot = self.bot
        q = basics.contentq(context.message.content, split=False)
        if "[dm]" in q:
            bot = self.bot
            u = context.message.author

            if u.id in bot.dmdaily:
                bot.dmdaily.remove(u.id)
                await talking.reply(
                    context,
                    "You'll now be informed about getting a daily in the same channel."
                )
            else:
                bot.dmdaily.append(u.id)
                await talking.reply(
                    context,
                    "You'll now be informed about getting a daily in a DM.")
            basics.save(bot, "dmdaily")
            return
        if "[list]" in q:
            lol = [["User", "Last", "Today"]]
            for k, i in self.bot.sdailylast[context.message.guild.id].items():
                try:
                    m = utility.get_member_or_user(bot, context.message.guild,
                                                   int(k))
                    if m is not None:
                        lol.append([
                            basics.truename(bot, m),
                            i.replace("DEFAULT", ""),
                            i == str(datetime.utcnow().date())
                        ])
                except ValueError:
                    pass
            SortableChart(bot,
                          validfor=timedelta(minutes=10),
                          context=context,
                          lol=lol,
                          initialsort=[0, 1],
                          defaultreverse={1})
            return

        id = str(context.message.author.id)
        if id not in self.bot.sdailylast[context.message.guild.id].keys():
            if id + "DISABLED" in self.bot.sdailylast[
                    context.message.guild.id].keys():
                self.bot.sdailylast[context.message.guild.id][id] = \
                self.bot.sdailylast[context.message.guild.id][id + "DISABLED"]
                del self.bot.sdailylast[context.message.guild.id][id +
                                                                  "DISABLED"]
            else:
                self.bot.sdailylast[context.message.guild.id][id] = "DEFAULT"
            basics.save(self.bot, "sdailylast")
            await talking.reply(
                context,
                "You will now be offered once a day after a random message three potential people to give a token to. Use this command again to turn it off.",
                reaction=True)
            return
        else:
            self.bot.sdailylast[context.message.guild.id][
                id +
                "DISABLED"] = self.bot.sdailylast[context.message.guild.id][id]
            del self.bot.sdailylast[context.message.guild.id][id]
            basics.save(self.bot, "sdailylast")
            await talking.reply(
                context,
                "You've opted back out of dailies. Use this command again to pick up where you left off."
            )
            return
Exemple #13
0
    async def give(self, context):
        """Gives x Obama Tokens to the mentioned user."""
        async def SAVETODICT_give(self):
            bot = self.bot
            gifter = self.gifter
            giftee = self.giftee
            value = self.cost

            giftertokens = ot.otedit(self.bot,
                                     gifter,
                                     0,
                                     False,
                                     channel=context.message.channel)
            gifteetokens = ot.otedit(self.bot,
                                     giftee,
                                     0,
                                     False,
                                     channel=context.message.channel)

            ot.otedit(self.bot,
                      gifter,
                      -value,
                      False,
                      channel=context.message.channel)
            ot.otedit(self.bot,
                      giftee,
                      value,
                      False,
                      channel=context.message.channel)

            self.message = "You've given `{}` Obama Token{} to {}.\n\n{}'s Tokens:\n{} ➔ {}\n\n{}'s Tokens:\n{} ➔ {}".format(
                value, ["", "s"][value != 1], basics.truename(bot, giftee),
                basics.truename(bot, gifter), giftertokens,
                round(giftertokens - value, 2), basics.truename(bot, giftee),
                gifteetokens, round(gifteetokens + value, 2))
            await AchievementBrowser.ach_check(bot, gifter,
                                               self.context.message.channel,
                                               "give", {
                                                   "giftee": giftee,
                                                   "value": value
                                               })

        ammount = basics.contentq(context.message.content)
        bot = self.bot
        value = re.sub("[^0-9\.]", "",
                       re.sub("<@!?[0-9]{18}>", "", " ".join(ammount)))
        gifter = context.message.author
        giftertokens = ot.otedit(self.bot,
                                 gifter,
                                 0,
                                 True,
                                 channel=context.message.channel)

        if len(value) == 0:
            await talking.reply(context, "Please give a value!")
            return
        value = round(float(value), 2)
        if len(context.message.mentions) == 0:
            await talking.reply(context, "Please mention someone!")
            return
        if context.message.mentions[0] == gifter:
            await talking.reply(context,
                                "You can't give Obama Tokens to yourself!")
            return

        giftee = context.message.mentions[0]
        gifteetokens = ot.otedit(self.bot,
                                 giftee,
                                 0,
                                 True,
                                 channel=context.message.channel)
        message = "Are you sure you want to give `{}` Obama Token{} to {}?\n\n{}'s Tokens:\n{} ➔ {}\n\n{}'s Tokens:\n{} ➔ {}".format(
            value, ["", "s"][value != 1], basics.truename(bot, giftee),
            basics.truename(bot, gifter), giftertokens,
            round(giftertokens - value, 2), basics.truename(bot, giftee),
            gifteetokens, round(gifteetokens + value, 2))

        ConfirmMessage(bot,
                       validfor=timedelta(minutes=5),
                       message=message,
                       gifter=gifter,
                       giftee=giftee,
                       cost=value,
                       yesscript=SAVETODICT_give,
                       context=context)
Exemple #14
0
    async def obamatokens(self, context):
        """Shows how many Obama Tokens you have. Mention somebody to check how much they have instead.

        Use [all] to see how many everyone has and their maxes, sorted by their maxes. Use [now] to sort by how many they have instead. Use [visual] to see it in emojis."""
        q = basics.contentq(context.message.content)
        bot = self.bot

        ot.otedit(self.bot,
                  context.message.author,
                  0,
                  False,
                  channel=context.message.channel)
        if "[all]" in " ".join(q) or "[now]" in " ".join(
                q) or "[top]" in " ".join(q) or "[max]" in " ".join(q):
            l = [["User", "Max", "Now", "Given", "Me", "Mentioned"]]
            for k in self.bot.obamatokens[context.message.guild.id].keys():
                k = context.message.guild.get_member(k)
                if k is None:
                    continue
                ot.otedit(self.bot,
                          k,
                          0,
                          False,
                          channel=context.message.channel)
                if k != None:
                    l.append([
                        basics.truename(bot, k),
                        float(self.bot.obamatokensmax[context.message.guild.id]
                              [k.id]),
                        float(self.bot.obamatokens[context.message.guild.id][
                            k.id]),
                        float(self.bot.obamatokensgiven[
                            context.message.guild.id][k.id]),
                        k.id == context.message.author.id, k
                        in context.message.mentions
                    ])

            # charlst = [["User", "Max", "Now", "Given", "Me","Mentioned"]]
            # for n, x in enumerate(l):
            #     max = str(x[0])
            #     if "." not in max:
            #         max += "."
            #     while list(max).index(".") > len(max) - 3:
            #         max += "0"
            #
            #     now = str(x[2])
            #     if "." not in now:
            #         now += "."
            #     while list(now).index(".") > len(now) - 3:
            #         now += "0"
            #     charlst.append([x[1], max, now, x[3], x[4], x[5]])

            SortableChart(bot,
                          validfor=timedelta(minutes=5),
                          context=context,
                          lol=l,
                          initialsort=[5, 1, 4, 2, 3, 6],
                          addnumbers=True,
                          resetnumbers={2, 3, 4},
                          defaultreverse={2, 3, 4, 5, 6})

            return
        target = context.message.author
        if len(context.message.mentions) > 0:
            target = context.message.mentions[0]
            ot.otedit(self.bot,
                      target,
                      0,
                      False,
                      channel=context.message.channel)
        if "[visual]" in " ".join(q):
            if target == context.message.author:
                targetstr = "Your"
            else:
                targetstr = "{}'s".format(shownames(target))
            await talking.saysplit(
                self,
                "{} current Obama Tokens:\n{}\n\n{} all-time Obama Tokens:\n{}"
                .format(
                    targetstr,
                    ot.visualtokens(self.bot.obamatokens[target.id] / 0.04),
                    targetstr,
                    ot.visualtokens(self.bot.obamatokensmax[target.id] /
                                    0.04)), [">"])
        else:
            if target == context.message.author:
                targetstr = "You currently have"
                targetstr2 = "Your"
            else:
                targetstr = "{} currently has".format(mf.shownames(target))
                targetstr2 = "Their".format(mf.shownames(target))
            await talking.reply(
                context,
                "{} {} Obama Tokens, {} of which were given. {} all-time count is {}."
                .format(targetstr,
                        self.bot.obamatokens[target.guild.id][target.id],
                        self.bot.obamatokensgiven[target.guild.id][target.id],
                        targetstr2,
                        self.bot.obamatokensmax[target.guild.id][target.id]))