Ejemplo n.º 1
0
    async def listm(self, ctx):
        """!settings modified"""
        language = prefs.getPref(ctx.message.server, "language")
        defaultSettings = commons.defaultSettings
        x = PrettyTable()

        x._set_field_names([
            _("Parameter", language),
            _("Value", language),
            _("Default value", language)
        ])
        for param in defaultSettings.keys():
            if prefs.getPref(ctx.message.server,
                             param) != defaultSettings[param]["value"]:
                x.add_row([
                    param,
                    prefs.getPref(ctx.message.server, param),
                    defaultSettings[param]["value"]
                ])

        await comm.message_user(
            ctx.message,
            _("List of modified parameters : \n```{table}```",
              language).format(
                  **{"table": x.get_string(sortby=_("Parameter", language))}))
Ejemplo n.º 2
0
    async def del_admin(self, ctx, target: discord.Member):
        """!del_admin [target]
        Remove an admin from the server
        """
        language = prefs.getPref(ctx.message.server, "language")
        servers = prefs.JSONloadFromDisk("channels.json")
        if target.id in servers[ctx.message.server.id]["admins"]:
            servers[ctx.message.server.id]["admins"].remove(target.id)
            await comm.logwithinfos_ctx(ctx, "Deleting admin {admin_name} | {admin_id} from configuration file for server {server_name} | {server_id}.".format(**{
                "admin_name" : target.name,
                "admin_id"   : target.id,
                "server_name": ctx.message.server.name,
                "server_id"  : ctx.message.server.id
            }))
            await comm.message_user(ctx.message, _(":robot: OK, {name} is not an admin anymore!", language).format(**{
                "name": target.name
            }))

            prefs.JSONsaveToDisk(servers, "channels.json")


        else:
            await comm.message_user(ctx.message, _(":robot: {name} is not an admin!", language).format(**{
                "name": target.name
            }))
Ejemplo n.º 3
0
    async def set(self, ctx, pref: str, value: str):
        """!settings set [pref] [value]
        Admin powers required"""
        language = prefs.getPref(ctx.message.server, "language")

        if pref in commons.defaultSettings.keys():
            try:
                if pref == "ducks_per_day":
                    maxCJ = int(125 + (ctx.message.server.member_count / (5 + (ctx.message.server.member_count / 300))))
                    if int(value) > maxCJ:
                        if ctx.message.author.id in commons.owners:
                            await comm.message_user(ctx.message, _("Bypassing the max_ducks_per_day check as you are the bot owner. It would have been `{max}`.", language).format(**{
                                "max": maxCJ
                            }))
                        else:
                            value = maxCJ
            except (TypeError, ValueError):
                await comm.message_user(ctx.message, _(":x: Incorrect value.", language))
                return

            if prefs.setPref(ctx.message.server, pref=pref, value=value):
                if pref == "ducks_per_day":
                    await ducks.planifie(ctx.message.channel)
                await comm.message_user(ctx.message, _(":ok: The setting {pref} has been set to `{value}` on this server.", language).format(**{
                    "value": prefs.getPref(ctx.message.server, pref),
                    "pref" : pref
                }))
            else:
                await comm.message_user(ctx.message, _(":x: Incorrect value.", language))
        else:
            await comm.message_user(ctx.message, _(":x: Invalid preference, maybe a typo? Check the list with `!settings list`", language))
Ejemplo n.º 4
0
 async def claimserver(self, ctx):
     """Sets yourself as an admin if there are no admin configured, IE: when you just added the bot to a server
     !claimserver"""
     language = prefs.getPref(ctx.message.server, "language")
     servers = prefs.JSONloadFromDisk("channels.json")
     if not ctx.message.server.id in servers:
         servers[ctx.message.server.id] = {}
     if not "admins" in servers[ctx.message.server.id] or not servers[
             ctx.message.server.id]["admins"]:
         servers[ctx.message.server.id]["admins"] = [ctx.message.author.id]
         await comm.logwithinfos_ctx(
             ctx,
             "Adding admin {admin_name} | {admin_id} to configuration file for server {server_name} | {server_id}."
             .format(
                 **{
                     "admin_name": ctx.message.author.name,
                     "admin_id": ctx.message.author.id,
                     "server_name": ctx.message.server.name,
                     "server_id": ctx.message.server.id
                 }))
         await comm.message_user(
             ctx.message,
             _(":robot: OK, you've been set as an admin!", language))
     else:
         await comm.logwithinfos_ctx(ctx, "An admin already exist")
         await comm.message_user(
             ctx.message,
             _(
                 ":x: This server has already been claimed! Try !add_admin instead.",
                 language))
     prefs.JSONsaveToDisk(servers, "channels.json")
Ejemplo n.º 5
0
    async def add_channel(self, ctx):
        """Add the current channel to the server
        !add_channel
        """
        language = prefs.getPref(ctx.message.server, "language")
        servers = prefs.JSONloadFromDisk("channels.json")
        if not "channels" in servers[ctx.message.server.id]:
            servers[ctx.message.server.id]["channels"] = []

        if not ctx.message.channel.id in servers[
                ctx.message.server.id]["channels"]:
            await comm.logwithinfos_ctx(
                ctx, "Adding channel {name} | {id} to channels.json...".format(
                    **{
                        "id": ctx.message.channel.id,
                        "name": ctx.message.channel.name
                    }))
            servers[ctx.message.server.id]["channels"] += [
                ctx.message.channel.id
            ]
            prefs.JSONsaveToDisk(servers, "channels.json")
            await ducks.planifie(ctx.message.channel)
            await comm.message_user(ctx.message,
                                    _(":robot: Channel added!", language))

        else:
            await comm.logwithinfos_ctx(ctx, "Channel exists")
            await comm.message_user(
                ctx.message,
                _(":x: This channel already exists in the game.", language))
Ejemplo n.º 6
0
    async def view(self, ctx, pref: str):
        """!settings view [pref]"""
        language = prefs.getPref(ctx.message.server, "language")

        if pref in commons.defaultSettings.keys():
            await comm.message_user(ctx.message, _("The {pref} setting's value is set to `{value}` on this server.", language).format(**{
                "value": prefs.getPref(ctx.message.server, pref),
                "pref" : pref
            }))
        else:
            await comm.message_user(ctx.message, _(":x: Invalid preference, maybe a typo? Check the list with `!settings list`.", language))
Ejemplo n.º 7
0
 async def give_exp(self, ctx, target: discord.Member, exp: int):
     """Give exp to a player.
     Require admin powers
     !give_exp [target] [exp]"""
     try:
         scores.addToStat(ctx.message.channel, target, "exp", exp)
     except OverflowError:
         await comm.message_user(ctx.message, _("Congratulations, you sent / gave more experience than the maximum number I'm able to store.", prefs.getPref(ctx.message.server, "language")))
         return
     await comm.logwithinfos_ctx(ctx, "[giveexp] Giving " + str(exp) + " exp points to " + target.mention)
     await comm.message_user(ctx.message, _(":ok:, they now have {newexp} exp points!", prefs.getPref(ctx.message.server, "language")).format(**{
         "newexp": scores.getStat(ctx.message.channel, target, "exp")
     }))
Ejemplo n.º 8
0
    async def reset(self, ctx, pref: str):
        """!settings reset [pref]
        Admin powers required"""
        language = prefs.getPref(ctx.message.server, "language")

        if pref in commons.defaultSettings.keys():
            prefs.setPref(ctx.message.server, pref)
            await comm.message_user(ctx.message, _(":ok: The setting {pref} has been reset to its defalut value: `{value}`.", language).format(**{
                "value": prefs.getPref(ctx.message.server, pref),
                "pref" : pref
            }))
        else:
            await comm.message_user(ctx.message, _(":x: Invalid preference, maybe a typo? Check the list with `!settings list`", language))
Ejemplo n.º 9
0
 async def broadcast(self, ctx, *, bc: str):
     """!broadcast [message]"""
     language = prefs.getPref(ctx.message.server, "language")
     await comm.message_user(ctx.message,
                             _("Starting the broadcast", language))
     await comm.logwithinfos_ctx(ctx, "Broadcast started")
     for channel in list(commons.ducks_planned.keys()):
         try:
             await self.bot.send_message(channel, bc)
         except:
             await comm.logwithinfos_ctx(
                 ctx, "Error broadcasting to " + str(channel.name))
             pass
     await comm.logwithinfos_ctx(ctx, "Broadcast ended")
     await comm.message_user(ctx.message, _("Broadcast finished", language))
Ejemplo n.º 10
0
    async def purge_messages_criteria(self, ctx, *, remove: str):
        language = prefs.getPref(ctx.message.server, "language")
        import datetime
        weeks = datetime.datetime.now() - datetime.timedelta(days=13)

        if ctx.message.channel.permissions_for(ctx.message.server.me).manage_messages:
            def check(m):
                return remove in m.content and not m.timestamp < weeks

            deleted = await ctx.bot.purge_from(ctx.message.channel, limit=100, check=check)
            await comm.message_user(ctx.message, _("{deleted} message(s) deleted", language).format(**{
                "deleted": len(deleted)
            }))
        else:
            await comm.message_user(ctx.message, _("No messages deleted: permission denied.", language))
Ejemplo n.º 11
0
 async def permissions(self, ctx):
     """Check permissions given to the bot. You'll need admin powers
     !permissions"""
     permissionsToHave = [
         "change_nicknames", "connect", "create_instant_invite",
         "embed_links", "manage_messages", "mention_everyone",
         "read_messages", "send_messages", "send_tts_messages"
     ]
     permissions_str = ""
     for permission, value in ctx.message.server.me.permissions_in(
             ctx.message.channel):
         if value:
             emo = ":white_check_mark:"
         else:
             emo = ":negative_squared_cross_mark:"
         if (value and permission in permissionsToHave) or (
                 not value and not permission in permissionsToHave):
             pass
         else:
             emo += ":warning:"
         permissions_str += "\n{value}\t{name}".format(
             **{
                 "value": emo,
                 "name": str(permission)
             })
     await comm.message_user(
         ctx.message,
         _("Permissions: {permissions}",
           prefs.getPref(
               ctx.message.server,
               "language")).format(**{"permissions": permissions_str}))
Ejemplo n.º 12
0
    async def game_unban(self, ctx, member: discord.Member):
        """Unban someone from the bot on the current channel
        !game_unban [member]"""
        language = prefs.getPref(ctx.message.server, "language")

        scores.setStat(ctx.message.channel, member, "banned", False)
        await comm.message_user(ctx.message, _(":ok: Done, user unbanned. :eyes:", language))
Ejemplo n.º 13
0
 def check(ctx, exp, warn):
     exp_ = have_exp_check(ctx.message, exp)
     if not exp_ and warn:
         commons.bot.loop.create_task(comm.message_user(ctx.message, _(":x: You can't use this command, you don't have at least {exp} exp points!", prefs.getPref(ctx.message.server, "language")).format(**{
             "exp": exp
         })))
     return exp_
Ejemplo n.º 14
0
    async def purgemessages(self, ctx, number: int = 500):
        """Delete last messages in the channel
        !purgemessages <number of messages>"""
        language = prefs.getPref(ctx.message.server, "language")
        import datetime
        weeks = datetime.datetime.now() - datetime.timedelta(days=13)

        if ctx.message.channel.permissions_for(ctx.message.server.me).manage_messages:
            def not_pinned(m):
                return not m.pinned and not m.timestamp < weeks

            deleted = await self.bot.purge_from(ctx.message.channel, limit=number, check=not_pinned)
            await comm.message_user(ctx.message, _("{deleted} message(s) deleted.", language).format(**{
                "deleted": len(deleted)
            }))
        else:
            await comm.message_user(ctx.message, _("No messages deleted: permission denied.", language))
Ejemplo n.º 15
0
    async def ping(self, ctx):
        language = getPref(ctx.message.server, "language")
        current_time = time.time()
        # TODO: ensure_soon?
        ping_msg = await comm.message_user(
            ctx.message,
            _("BANG OR BANG, what's the best? :p\nAnyway I'm up and running!",
              language))
        new_time = time.time(
        )  # Just f*****g imprécis cela dit, a cause du await...

        send_delay = int(round((new_time * 1000) - (current_time * 1000)))
        if send_delay > 0:  # Si l'OS supporte la précision à la milliseconde
            await self.bot.edit_message(
                ping_msg,
                ping_msg.content + _("\n\n`This message took {ms}ms to send.`",
                                     language).format(ms=send_delay))
Ejemplo n.º 16
0
 async def deleteeverysinglescoreandstatonthischannel(self, ctx):
     """Delete scores and stats of players on this channel. You'll need admin powers
     !deleteeverysinglescoreandstatonthischannel"""
     scores.delChannelPlayers(ctx.message.channel)
     await comm.message_user(
         ctx.message,
         _(":ok: Scores / stats of the channel were successfully deleted.",
           prefs.getPref(ctx.message.server, "language")))
Ejemplo n.º 17
0
 async def duckplanning(self, ctx):
     """!duckplanning
     DEPRECATED! Get the number of ducks left to spawn on the channel
     """
     await comm.message_user(
         ctx.message,
         _("There are {ducks} ducks left to spawn today!",
           prefs.getPref(ctx.message.server, "language")).format(
               ducks=commons.ducks_planned[ctx.message.channel]))
Ejemplo n.º 18
0
 async def del_channel(self, ctx):
     """!del_channel
     Remove the current channel from the server
     """
     await ducks.del_channel(ctx.message.channel)
     await comm.message_user(
         ctx.message,
         _(":ok: Channel deleted.",
           prefs.getPref(ctx.message.server, "language")))
Ejemplo n.º 19
0
    async def list(self, ctx):
        """!settings list"""
        language = prefs.getPref(ctx.message.server, "language")

        await comm.message_user(
            ctx.message,
            _(
                "The list of preferences is available on our new website: https://api-d.com/bot-settings.html",
                language))
Ejemplo n.º 20
0
    async def settings(self, ctx):
        language = prefs.getPref(ctx.message.server, "language")

        if not ctx.invoked_subcommand:
            await comm.message_user(
                ctx.message,
                _(
                    ":x: Incorrect syntax. Use the command this way: `!settings [view/set/reset/list/modified] [setting if applicable]`",
                    language))
Ejemplo n.º 21
0
 def check(ctx, warn):
     admin = is_owner_check(ctx.message) or is_admin_check(ctx.message)
     if not admin and warn:
         commons.bot.loop.create_task(
             comm.message_user(
                 ctx.message,
                 _(
                     ":x: You can't use this command, you're not an admin on this server!",
                     prefs.getPref(ctx.message.server, "language"))))
     return admin
Ejemplo n.º 22
0
 def check(ctx, warn):
     owner = is_owner_check(ctx.message)
     if not owner and warn:
         commons.bot.loop.create_task(
             comm.message_user(
                 ctx.message,
                 _(
                     ":x: You can't use this command, you're not the bot owner!",
                     prefs.getPref(ctx.message.server, "language"))))
     return owner
Ejemplo n.º 23
0
    async def time(self, ctx):
        time_data = int(time.time()) % 86400
        hour = str(int(time_data / 60 / 60)).rjust(2, "0")
        minutes = str(int(time_data / 60 % 60)).rjust(2, "0")
        seconds = str(int(time_data % 60)).rjust(2, "0")

        await comm.message_user(
            ctx.message,
            _("It's {hour}:{minutes}:{seconds}.",
              getPref(ctx.message.server, "language")).format(hour=hour,
                                                              minutes=minutes,
                                                              seconds=seconds))
Ejemplo n.º 24
0
    async def reload(self, ctx):
        await self.giveBackIfNeeded(ctx.message)
        message = ctx.message
        language = prefs.getPref(message.server, "language")

        if scores.getStat(message.channel, message.author, "confisque", default=False):
            await comm.message_user(message, _("Your weapon is confiscated.", language))
            return
        if scores.getStat(message.channel, message.author, "enrayee", default=False):
            await comm.message_user(message, _("You unjammed your weapon.", language))
            scores.setStat(message.channel, message.author, "enrayee", False)
            # TODO : simplifier
            if scores.getStat(message.channel, message.author, "balles", default=scores.getPlayerLevel(message.channel, message.author)["balles"]) > 0:
                return

        if scores.getStat(message.channel, message.author, "balles", default=scores.getPlayerLevel(message.channel, message.author)["balles"]) <= 0:
            if scores.getStat(message.channel, message.author, "chargeurs", default=scores.getPlayerLevel(message.channel, message.author)["chargeurs"]) > 0:
                scores.setStat(message.channel, message.author, "balles", scores.getPlayerLevel(message.channel, message.author)["balles"])
                scores.addToStat(message.channel, message.author, "chargeurs", -1)
                scores.addToStat(message.channel, message.author, "reloads", 1)
                greet = _("You reloaded your weapon.", language)
            else:
                greet = _("You don't have any ammo left!", language)
                scores.addToStat(message.channel, message.author, "reloads_without_chargers", 1)
        else:
            greet = _("You don't need to reload your weapon.", language)
            scores.addToStat(message.channel, message.author, "unneeded_reloads", 1)

        await comm.message_user(message, _("{greet} | Ammo in weapon: {balles_actuelles}/{balles_max} | Chargers left: {chargeurs_actuels}/{chargeurs_max}", language).format(**{
            "greet"            : greet,
            "balles_actuelles" : scores.getStat(message.channel, message.author, "balles", default=scores.getPlayerLevel(message.channel, message.author)["balles"]),
            "balles_max"       : scores.getPlayerLevel(message.channel, message.author)["balles"],
            "chargeurs_actuels": scores.getStat(message.channel, message.author, "chargeurs", default=scores.getPlayerLevel(message.channel, message.author)["chargeurs"]),
            "chargeurs_max"    : scores.getPlayerLevel(message.channel, message.author)["chargeurs"]
        }))
Ejemplo n.º 25
0
    async def send_message(self, ctx, server_name: str, channel_name: str, *,
                           message: str):
        language = prefs.getPref(ctx.message.server, "language")

        await self.bot.send_message(
            discord.utils.find(
                lambda m: m.name == channel_name,
                discord.utils.find(
                    lambda m: m.name == server_name or str(m.id) == str(
                        server_name), self.bot.servers).channels), message)
        await comm.message_user(
            ctx.message,
            _("Message ({message}) sent to {server} #{channel} ",
              language).format(message=message,
                               server=server_name,
                               channel=channel_name))
Ejemplo n.º 26
0
def addToStat(channel, player, stat, value, announce=True):
    cond = stat == "exp" and prefs.getPref(channel.server, "announce_level_up") and announce
    if cond:
        ancien_niveau = getPlayerLevel(channel, player)

    setStat(channel, player, stat, int(getStat(channel, player, stat)) + value)

    if cond:
        language = prefs.getPref(channel.server, "language")

        embed = discord.Embed(description=_("Level of {player} on #{channel}", language).format(**{
            "player" : player.name,
            "channel": channel.name
        }))

        level = getPlayerLevel(channel, player)
        if ancien_niveau["niveau"] > level["niveau"]:
            embed.title = _("You leveled down!", language)
            embed.colour = discord.Colour.red()
        elif ancien_niveau["niveau"] < level["niveau"]:
            embed.title = _("You leveled up!", language)
            embed.colour = discord.Colour.green()
        else:
            return

        embed.set_thumbnail(url=player.avatar_url if player.avatar_url else commons.bot.user.avatar_url)
        embed.url = 'https://api-d.com/'

        embed.add_field(name=_("Current level", language), value=str(level["niveau"]) + " (" + _(level["nom"], language) + ")")
        embed.add_field(name=_("Previous level", language), value=str(ancien_niveau["niveau"]) + " (" + _(ancien_niveau["nom"], language) + ")")
        embed.add_field(name=_("Shots accuracy", language), value=str(level["precision"]))
        embed.add_field(name=_("Weapon reliability", language), value=str(level["fiabilitee"]))
        embed.add_field(name=_("Exp points", language), value=str(getStat(channel, player, "exp")))
        embed.set_footer(text='DuckHunt V2', icon_url='http://api-d.com/snaps/2016-11-19_10-38-54-q1smxz4xyq.jpg')
        try:
            commons.bot.loop.create_task(commons.bot.send_message(channel, embed=embed))
        except:
            commons.logger.exception("error sending embed, with embed " + str(embed.to_dict()))
            commons.bot.loop.create_task(commons.bot.send_message(channel, _(":warning: There was an error while sending the embed, please check if the bot has the `embed_links` permission and try again!", language)))
Ejemplo n.º 27
0
    async def add_admin(self, ctx, target: discord.Member):
        """!add_admin [target]
        Remove an admin to the server
        """
        language = prefs.getPref(ctx.message.server, "language")
        servers = prefs.JSONloadFromDisk("channels.json")
        servers[ctx.message.server.id]["admins"] += [target.id]
        await comm.logwithinfos_ctx(ctx, "Adding admin {admin_name} | {admin_id} to configuration file for server {server_name} | {server_id}.".format(**{
            "admin_name" : target.name,
            "admin_id"   : target.id,
            "server_name": ctx.message.server.name,
            "server_id"  : ctx.message.server.id
        }))
        await comm.message_user(ctx.message, _(":robot: OK, {name} was set as an admin on the server!", language).format(**{
            "name": target.name
        }))

        prefs.JSONsaveToDisk(servers, "channels.json")
Ejemplo n.º 28
0
    async def cleanup_servers(self, ctx):
        language = prefs.getPref(ctx.message.server, "language")

        await comm.message_user(ctx.message,
                                _("Serching for servers to leave", language))
        to_clean = []
        total_members_lost = 0
        servers = JSONloadFromDisk("channels.json", default="{}")

        for server in list(self.bot.servers):

            try:
                if len(servers[server.id]["channels"]) == 0:
                    to_clean.append(server)
                    total_members_lost += server.member_count

            except KeyError:  # Pas de channels ou une autre merde dans le genre ?
                to_clean.append(server)
                total_members_lost += server.member_count

        def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
            return ''.join(random.choice(chars) for _ in range(size))

        random_str = id_generator()

        await comm.message_user(
            ctx.message,
            _(
                "Cleaning {servers} unused servers (accounting for {members} members in total)",
                language).format(servers=len(to_clean),
                                 members=total_members_lost))
        await comm.message_user(
            ctx.message,
            _("To confirm, please type {random_str} now.",
              language).format(random_str=random_str))

        def is_random_str(m):
            return m.content == random_str

        guess = await self.bot.wait_for_message(timeout=10.0,
                                                author=ctx.message.author,
                                                check=is_random_str)

        if guess is None:
            await comm.message_user(
                ctx.message,
                _(":x: Operation canceled, you took too long to answer.",
                  language).format(random_str=random_str))

        else:
            failed = 0
            for server in to_clean:
                try:
                    await self.bot.send_message(
                        server,
                        ":warning: I'll now leave the server, as you have not configured me... Join https://discord.gg/2BksEkV the duckhunt server for help about the setup and actions you have to take to bring me back."
                    )
                except:
                    failed += 1
                    pass
                try:
                    await self.bot.leave_server(server)  # Good Bye :'(
                except:
                    commons.logger.exception("")

            await comm.message_user(
                ctx.message,
                _(":ok: Finished, failed for {failed} servers.",
                  language).format(failed=failed))
Ejemplo n.º 29
0
    async def bang(self, ctx):
        now = time.time()
        message = ctx.message
        channel = message.channel
        author = message.author

        language = prefs.getPref(message.server, "language")
        await self.giveBackIfNeeded(message)

        if scores.getStat(channel, author, "mouille") > int(now):  # Water
            await comm.message_user(
                message,
                _(
                    "Your clothes are wet, you can't go hunting! Wait {temps_restant} minutes.",
                    language).format(
                        **{
                            "temps_restant":
                            int((scores.getStat(channel, author, "mouille") -
                                 int(time.time())) / 60)
                        }))
            scores.addToStat(channel, author, "shoots_tried_while_wet", 1)
            return

        if scores.getStat(channel, author, "confisque",
                          default=False):  # No weapon
            await comm.message_user(message,
                                    _("You don't have a weapon.", language))
            scores.addToStat(channel, author, "shoots_without_weapon", 1)
            return

        if scores.getStat(channel, author, "enrayee", default=False):  # Jammed
            await comm.message_user(
                message,
                _("Your weapon is jammed, it must be reloaded to unjam it.",
                  language))
            scores.addToStat(channel, author, "shoots_with_jammed_weapon", 1)
            return

        if scores.getStat(channel, author, "sabotee",
                          default="-") is not "-":  # Sabotaged
            await comm.message_user(
                message,
                _(
                    "Your weapon is sabotaged, thank {assaillant} for this bad joke.",
                    language).format(
                        **{
                            "assaillant":
                            scores.getStat(
                                channel, author, "sabotee", default="-")
                        }))
            scores.addToStat(channel, author, "shoots_sabotaged", 1)
            scores.setStat(channel, author, "enrayee", True)
            scores.setStat(channel, author, "sabotee", "-")
            return

        if scores.getStat(
                channel,
                author,
                "balles",
                default=scores.getPlayerLevel(
                    channel,
                    author)["balles"]) <= 0:  # No more bullets in charger
            await comm.message_user(
                message,
                _(
                    "** CHARGER EMPTY ** | Ammunition in the weapon: {balles_actuelles} / {balles_max} | Magazines remaining: {chargeurs_actuels} / {chargeurs_max}",
                    language).format(
                        **{
                            "balles_actuelles":
                            scores.getStat(channel,
                                           author,
                                           "balles",
                                           default=scores.getPlayerLevel(
                                               channel, author)["balles"]),
                            "balles_max":
                            scores.getPlayerLevel(channel, author)["balles"],
                            "chargeurs_actuels":
                            scores.getStat(channel,
                                           author,
                                           "chargeurs",
                                           default=scores.getPlayerLevel(
                                               channel, author)["chargeurs"]),
                            "chargeurs_max":
                            scores.getPlayerLevel(channel, author)["chargeurs"]
                        }))
            scores.addToStat(channel, author, "shoots_without_bullets", 1)
            return

        fiabilite = scores.getPlayerLevel(channel, author)["fiabilitee"]

        if scores.getStat(channel, author, "sand", default=False):
            fiabilite /= 2
            scores.setStat(channel, author, "sand", False)

        if not random.randint(1, 100) <= fiabilite and not (scores.getStat(
                channel, author,
                "graisse") > int(now)):  # Weapon jammed just now
            await comm.message_user(
                message,
                _("Your weapon just jammed, reload it to unjam it.", language))
            scores.addToStat(channel, author, "shoots_jamming_weapon", 1)
            scores.setStat(channel, author, "enrayee", True)
            return

        current_duck = None

        if commons.ducks_spawned:
            for duck in commons.ducks_spawned:
                if duck["channel"] == channel:
                    current_duck = duck
                    break

        if not current_duck and scores.getStat(
                channel, author,
                "detecteurInfra") > int(now) and scores.getStat(
                    channel, author, "detecteur_infra_shots_left"
                ) > 0:  # No ducks but infrared detector
            await comm.message_user(
                message,
                _(
                    "There isn't any duck in here, but the bullet wasn't fired because the infrared detector you added to your weapon is doing its job!",
                    language))
            scores.addToStat(channel, author, "shoots_infrared_detector", 1)
            scores.addToStat(channel, author, "detecteur_infra_shots_left", -1)
            return

        scores.addToStat(channel, author, "balles", -1)
        scores.addToStat(channel, author, "shoots_fired", 1)

        if not current_duck:  # No duck
            await self.sendBangMessage(
                message,
                _(
                    "Luckily you missed, but what were you aiming at exactly? There isn't any duck in here... [missed: -1 xp] [wild shot: -1 xp]",
                    language))
            scores.addToStat(channel, author, "exp", -2)
            scores.addToStat(channel, author, "shoots_no_duck", 1)
            return

        if random.randint(1, 100) <= prefs.getPref(
                message.server, "duck_frighten_chance") and scores.getStat(
                    channel, author,
                    "silencieux") < int(now):  # Duck frightened
            try:
                commons.ducks_spawned.remove(current_duck)
                commons.n_ducks_flew += 1
                scores.addToStat(channel, author, "exp", -1)
                await self.sendBangMessage(
                    message,
                    _(
                        "**FLAPP**\tFrightened by so much noise, the duck fled! CONGRATS! [missed: -1 xp]",
                        language))
                scores.addToStat(channel, author, "shoots_frightened", 1)
            except ValueError:
                await self.sendBangMessage(
                    message,
                    _("**PIEWW**\tYou missed the duck! [missed: -1 xp]",
                      language))
                scores.addToStat(channel, author, "shoots_missed", 1)
            return

        if scores.getStat(channel, author, "dazzled", True):
            accuracy = 200  # 50% moins de chance de toucher
            scores.setStat(channel, author, "dazzled", False)
        else:
            accuracy = 100

        precision = scores.getPlayerLevel(channel, author)["precision"]
        sight = scores.getStat(channel, author, "sight")
        if sight:
            precision += (100 - precision) / 3
            scores.setStat(channel, author, "sight", sight - 1)

        if random.randint(1, accuracy) > precision * prefs.getPref(
                message.server, "multiplier_miss_chance"):
            if random.randint(1, 100) <= prefs.getPref(
                    message.server,
                    "chance_to_kill_on_missed"):  # Missed and shot someone
                scores.addToStat(channel, author, "exp", -3)
                scores.addToStat(channel, author, "shoots_missed", 1)
                scores.addToStat(channel, author, "killed_players", 1)
                scores.setStat(channel, author, "confisque", True)

                memberlist = scores.getChannelPlayers(channel,
                                                      columns=['shoots_fired'])
                victim = None
                while not victim:
                    victim = random.choice(memberlist)
                    while not checks.is_player_check(victim):
                        memberlist.remove(victim)
                        victim = random.choice(memberlist)

                    victim = message.server.get_member(str(victim['id_']))

                if victim is not author:
                    await self.sendBangMessage(
                        message,
                        _(
                            "**BANG**\tYou missed the duck... and shot {player}! [missed: -1 xp] [hunting accident: -2 xp] [weapon confiscated]",
                            language).format(
                                **{
                                    "player":
                                    victim.mention if prefs.
                                    getPref(message.server, "killed_mentions"
                                            ) else victim.name
                                }))
                else:
                    await self.sendBangMessage(
                        message,
                        _(
                            "**BANG**\tYou missed the duck... and shot yourself! Maybe you should turn your weapon a little before shooting the next time? [missed: -1 xp] [hunting accident: -2 xp] [weapon confiscated]",
                            language))
                    scores.addToStat(channel, author, "self_killing_shoots", 1)

                if scores.getStat(channel, victim,
                                  "life_insurance") > int(now):
                    exp = int(
                        scores.getPlayerLevel(channel, author)["niveau"] / 2)
                    scores.addToStat(channel, victim, "exp", exp)
                    await self.bot.send_message(
                        channel,
                        str(victim.mention) +
                        _(" > You won {exp} with your life insurance !",
                          language).format(**{"exp": exp}))
                    scores.addToStat(channel, victim, "life_insurence_rewards",
                                     1)
            else:  # Missed and none was shot
                scores.addToStat(channel, author, "exp", -1)
                scores.addToStat(channel, author, "shoots_missed", 1)
                await self.sendBangMessage(
                    message,
                    _("**PIEWW**\tYou missed the duck! [missed: -1 xp]",
                      language))
            return

        if scores.getStat(channel, author, "explosive_ammo") > int(now):
            current_duck["SCvie"] -= 3
            vieenmoins = 3
            ono = _("BPAM", language)
        elif scores.getStat(channel, author, "ap_ammo") > int(now):
            current_duck["SCvie"] -= 2
            vieenmoins = 2
            ono = _("BAAM", language)
        else:
            current_duck["SCvie"] -= 1
            vieenmoins = 1
            ono = random.choice([_("BOUM", language), _("SPROTCH", language)])

        if current_duck["SCvie"] <= 0:  # Duck killed
            try:
                commons.ducks_spawned.remove(current_duck)
                commons.n_ducks_killed += 1
            except ValueError:
                await self.sendBangMessage(
                    message,
                    _(
                        "That was close, you almost killed the duck, but the other hunter got it first! [missed: -1 xp]",
                        language))
                scores.addToStat(channel, author, "exp", -1)
                scores.addToStat(channel, author, "shoots_missed", 1)
                scores.addToStat(channel, author, "shoots_almost_killed", 1)
                return

            exp = prefs.getPref(message.server, "exp_won_per_duck_killed")
            exp += prefs.getPref(
                message.server, "super_ducks_exp_multiplier") * (
                    current_duck["level"] - 1) * prefs.getPref(
                        message.server, "exp_won_per_duck_killed")
            if scores.getStat(channel, author, "trefle") >= time.time():
                toadd = scores.getStat(channel, author, "trefle_exp")
                exp += toadd
                scores.addToStat(channel, author, "exp_won_with_clover", toadd)

            exp = int(exp)

            scores.addToStat(channel, author, "exp", exp)
            scores.addToStat(channel, author, "killed_ducks", 1)
            if current_duck["level"] > 1:
                scores.addToStat(channel, author, "killed_super_ducks", 1)

            await self.sendBangMessage(
                message,
                _(
                    ":skull_crossbones: **{onomatopoeia}**\tYou killed the duck in {time} seconds, you are now at a grand total of {total} ducks (of which {supercanards} were super-ducks) killed on #{channel}.     \_X<   *COUAC*   [{exp} exp]",
                    language).format(
                        **{
                            "time":
                            round(now - current_duck["time"], 4),
                            "total":
                            scores.getStat(channel, author, "killed_ducks"),
                            "channel":
                            channel,
                            "exp":
                            exp,
                            "supercanards":
                            scores.getStat(channel, author,
                                           "killed_super_ducks"),
                            "onomatopoeia":
                            ono
                        }))
            if scores.getStat(channel,
                              author,
                              "best_time",
                              default=prefs.getPref(message.server,
                                                    "time_before_ducks_leave")
                              ) > float(now - current_duck["time"]):
                scores.setStat(channel, author, "best_time",
                               round(now - current_duck["time"], 6))
            if prefs.getPref(message.server, "users_can_find_objects"):
                rand = random.randint(0, 1000)
                HOUR = 3600
                DAY = 86400

                if rand <= 50:
                    scores.addToStat(channel, author, "trashFound", 1)
                    await comm.message_user(
                        message,
                        _(
                            "While searching in the bushes around the duck, you found **{inutilite}**.",
                            language).format(
                                **{
                                    "inutilite":
                                    _(random.choice(commons.inutilite),
                                      language)
                                }))

                elif rand <= 54:
                    c = scores.getStat(message.channel, message.author,
                                       "explosive_ammo")
                    if c > time.time():
                        scores.setStat(message.channel, message.author,
                                       "explosive_ammo", int(c + DAY))
                    else:
                        scores.setStat(message.channel,
                                       message.author, "explosive_ammo",
                                       int(time.time() + DAY))
                    scores.addToStat(message.channel, message.author,
                                     "found_explosive_ammo", 1)
                    await comm.message_user(
                        message,
                        _(
                            "While searching in the bushes around the duck, you found **a box of explosive ammo**.",
                            language))

                elif rand <= 60:
                    c = scores.getStat(message.channel, message.author,
                                       "explosive_ammo")
                    if c > time.time():
                        scores.setStat(message.channel, message.author,
                                       "explosive_ammo", int(c + DAY / 4))
                    else:
                        scores.setStat(message.channel, message.author,
                                       "explosive_ammo",
                                       int(time.time() + DAY / 4))
                    scores.addToStat(message.channel, message.author,
                                     "found_almost_empty_explosive_ammo", 1)
                    await comm.message_user(
                        message,
                        _(
                            "While searching in the bushes around the duck, you found **an almost empty box of explosive ammo**.",
                            language))

                elif rand <= 63:
                    scores.addToStat(message.channel, message.author,
                                     "found_chargers", 1)

                    if scores.getStat(message.channel,
                                      message.author,
                                      "chargeurs",
                                      default=scores.getPlayerLevel(
                                          message.channel, message.author)
                                      ["chargeurs"]) < scores.getPlayerLevel(
                                          message.channel,
                                          message.author)["chargeurs"]:
                        scores.addToStat(message.channel, message.author,
                                         "chargeurs", 1)
                        await comm.message_user(
                            message,
                            _(
                                "While searching in the bushes around the duck, you found **a full charger**.",
                                language))
                    else:
                        scores.addToStat(message.channel, message.author,
                                         "found_chargers_not_taken", 1)
                        await comm.message_user(
                            message,
                            _(
                                "While searching in the bushes around the duck, you found **a full charger**. You left it there, because your backpack is full.",
                                language))
                elif rand <= 70:
                    scores.addToStat(message.channel, message.author,
                                     "found_bullets", 1)
                    if scores.getStat(message.channel,
                                      message.author,
                                      "balles",
                                      default=scores.getPlayerLevel(
                                          message.channel, message.author)
                                      ["balles"]) < scores.getPlayerLevel(
                                          message.channel,
                                          message.author)["balles"]:
                        scores.addToStat(message.channel, message.author,
                                         "balles", 1)
                        await comm.message_user(
                            message,
                            _(
                                "While searching in the bushes around the duck, you found **a bullet**.",
                                language))

                    else:  # Shouldn't happen but we never know...
                        await comm.message_user(
                            message,
                            _(
                                "While searching in the bushes around the duck, you found **a bullet**. You left it there, because you have enough in your charger.",
                                language))
                        scores.addToStat(message.channel, message.author,
                                         "found_bullets_not_taken", 1)

        else:  # Duck harmed
            await self.sendBangMessage(
                message,
                _(
                    ":gun: The duck survived, try again! *SUPER DUCK DETECTED* [life: -{vie}]",
                    language).format(**{"vie": vieenmoins}))
            current_duck["SCvie"] -= vieenmoins
            scores.addToStat(channel, author, "shoots_harmed_duck", 1)
Ejemplo n.º 30
0
    async def serverlist(self,
                         ctx,
                         passed_prefs: str = "",
                         maxservs: int = None):
        language = prefs.getPref(ctx.message.server, "language")

        x = PrettyTable()
        args_ = passed_prefs.split(" ")
        x._set_field_names([
            _("Name", language),
            _("Invitation", language),
            _("Server ID", language),
            _("Number of enabled channels", language),
            _("Number of connected users", language),
            _("Ducks per day", language),
            _("Number of unneeded permissions", language),
            _("Number of needed permissions", language)
        ])
        x.reversesort = True

        tmp = await self.bot.send_message(
            ctx.message.channel,
            str(ctx.message.author.mention) + _(" > En cours", language))
        servers = JSONloadFromDisk("channels.json", default="{}")

        i = 0
        lu = 0

        slist = sorted(list(self.bot.servers),
                       key=lambda s: int(s.member_count),
                       reverse=True)[:maxservs]
        total = len(slist)

        for server in list(slist):
            i += 1
            if time.time() - lu >= 1.5 or i == total:
                lu = time.time()
                try:
                    await self.bot.edit_message(
                        tmp,
                        str(ctx.message.author.mention) +
                        _(" > Processing servers ({done}/{total})",
                          language).format(**{
                              "done": i,
                              "total": total
                          }))
                except:
                    pass
            invite = None

            permissionsToHave = [
                "change_nicknames", "connect", "create_instant_invite",
                "embed_links", "manage_messages", "mention_everyone",
                "read_messages", "send_messages", "send_tts_messages"
            ]

            permEnMoins = 0
            permEnPlus = 0
            channel = server.default_channel
            for permission, value in channel.permissions_for(server.me):
                if not value and permission in permissionsToHave:
                    permEnMoins += 1
                elif value and not permission in permissionsToHave:
                    permEnPlus += 1

            if "invitations" in args_:
                for channel in server.channels:
                    permissions = channel.permissions_for(server.me)
                    if permissions.create_instant_invite:
                        try:
                            invite = await self.bot.create_invite(channel,
                                                                  max_age=120 *
                                                                  60)
                            invite = invite.url
                        except:
                            invite = ""
                    else:
                        invite = ""
            try:
                channels = str(len(servers[server.id]["channels"]))
            except KeyError:  # Pas de channels ou une autre merde dans le genre ?
                channels = "0"

            x.add_row([
                server.name, invite,
                str(server.id), channels + "/" + str(len(server.channels)),
                server.member_count,
                prefs.getPref(server, "ducks_per_day"), permEnPlus, permEnMoins
            ])

        await comm.message_user(
            ctx.message, "```\n" +
            x.get_string(sortby=_("Number of connected users", language)) +
            "\n```")