Esempio n. 1
0
 async def say(self, ctx, channel: discord.TextChannel, *,
               message):  # p!say
     "Sends a message to a specified channel."
     checkChannel = self.bot.get_channel(channel.id)
     pollChannel = self.bot.get_channel(
         variables.VOTING)  # Channel #voting.
     if checkChannel == pollChannel:
         await ctx.send(
             f"{ctx.author.mention}, in order to send messages to {channel.mention}, please use `p!poll`."
         )
     else:
         async with channel.typing():
             characters = len(message)
             await asyncio.sleep(characters / 25)
         await channel.send(message,
                            allowed_mentions=discord.AllowedMentions(
                                everyone=True, roles=True, users=True))
         if channel != ctx.channel:
             embed = discord.Embed(color=0x80ff80)
             embed.add_field(name="Sent Message:",
                             value=message,
                             inline=False)
             await ctx.send(
                 f"{ctx.author.mention}, successfully sent the message to {channel.mention}.",
                 embed=embed)
Esempio n. 2
0
	async def send_message(self, channel: discord.TextChannel, message: str, delay=0.01):
		"""Sends a message to a channel with discord.typing()"""
		try:
			async with channel.typing():
				await asyncio.sleep(len(message) * delay)
				await self.bot.send_filtered(channel, content=message)
		except discord.Forbidden:
			pass  # Not allowed to send messages in this channel
Esempio n. 3
0
 async def make_info_channel_multiple_messages(channel: TextChannel, contents: List[AnyStr]) -> List[Message]:
     with channel.typing():
         messages: List[Message]
         ChannelManager.purge_channel(channel)
         for content in contents:
             message: Message = await channel.send("WIP")
             await message.edit(content=content)
             messages.append(message)
     return messages
Esempio n. 4
0
 async def send_message(self, channel: discord.TextChannel, message: str):
     """Send a mwessage to a channew.
     Wiww send a typing indicatow, and wiww wait a vawiabwe amount of time
     based on the wength of the text (to simuwate typing speed)
     """
     try:
         async with channel.typing():
             await asyncio.sleep(len(message) * 0.01)
             await self.bot.send_filtered(channel, content=message)
     except discord.Forbidden:
         pass  # Not awwowed to send mwessages in dis channew
Esempio n. 5
0
 async def triggertyping(self,
                         ctx,
                         duration: int,
                         channel: discord.TextChannel = None):
     """sends a typing indicator for a specified amount of time
     Parameters
     • duration - how long to keep the typing indicator running
     • channel - which channel to send the typing indicator in, defaults to the current channel
     """
     channel = channel or ctx.channel
     async with channel.typing():
         await asyncio.sleep(duration)
Esempio n. 6
0
    async def send_message(self, channel: discord.TextChannel, message: str):
        """Send a message to a channel.

        Will send a typing indicator, and will wait a variable amount of time
        based on the length of the text (to simulate typing speed)
        """
        try:
            async with channel.typing():
                await asyncio.sleep(len(message) * 0.01)
                await self.bot.send_filtered(channel, content=message)
        except discord.errors.Forbidden:
            pass  # Not allowed to send messages in this channel
Esempio n. 7
0
 async def type(self,
                ctx,
                duration=10,
                channel: discord.TextChannel = None):
     """
     Starts typing to a channel.
     """
     await ctx.message.add_reaction('🕓')
     if channel is None:
         channel = ctx.message.channel
     async with channel.typing():
         await asyncio.sleep(duration)
     await ctx.message.add_reaction('✅')
Esempio n. 8
0
 async def cmd_play(self, channel: discord.TextChannel, author: discord.Member, params: typing.List[str]):
     if len(params) < 2:
         await channel.send("⚠ Non hai specificato una canzone da riprodurre!\n"
                            "Sintassi: `!play <url|ricercayoutube|nomefile>`")
         return
     channel.typing()
     # If the radio messages are enabled...
     if self.radio_messages:
         self.next_radio_message_in -= 1
         if self.next_radio_message_in <= 0:
             radio_message = random.sample(radio_messages, 1)[0]
             self.next_radio_message_in = int(config["Discord"]["radio_messages_every"])
             await self.add_video_from_url(radio_message)
             await channel.send(f"📻 Aggiunto un messaggio radio, disattiva con `!radiomessages off`.")
     # Parse the parameter as URL
     url = re.match(r"(?:https?://|ytsearch[0-9]*:).*", " ".join(params[1:]).strip("<>"))
     if url is not None:
         # This is a url
         await self.add_video_from_url(url.group(0), enqueuer=author)
         await channel.send(f"✅ Video aggiunto alla coda.")
         return
     # Parse the parameter as file
     file_path = os.path.join(os.path.join(os.path.curdir, "opusfiles"), " ".join(params[1:]))
     if os.path.exists(file_path):
         # This is a file
         await self.add_video_from_file(file=file_path, enqueuer=author)
         await channel.send(f"✅ Video aggiunto alla coda.")
         return
     file_path += ".opus"
     if os.path.exists(file_path):
         # This is a file
         await self.add_video_from_file(file=file_path, enqueuer=author)
         await channel.send(f"✅ Video aggiunto alla coda.")
         return
     # Search the parameter on youtube
     search = " ".join(params[1:])
     # This is a search
     await self.add_video_from_url(url=f"ytsearch:{search}", enqueuer=author)
     await channel.send(f"✅ Video aggiunto alla coda.")
Esempio n. 9
0
File: reddit.py Progetto: vemel/bot
    async def send_top_posts(self,
                             channel: TextChannel,
                             subreddit: Subreddit,
                             content: str = None,
                             time: str = "all") -> Message:
        """Create an embed for the top posts, then send it in a given TextChannel."""
        # Create the new spicy embed.
        embed = Embed()
        embed.description = ""

        # Get the posts
        async with channel.typing():
            posts = await self.fetch_posts(route=f"{subreddit}/top",
                                           amount=5,
                                           params={"t": time})

        if not posts:
            embed.title = random.choice(ERROR_REPLIES)
            embed.colour = Colour.red()
            embed.description = (
                "Sorry! We couldn't find any posts from that subreddit. "
                "If this problem persists, please let us know.")

            return await channel.send(embed=embed)

        for post in posts:
            data = post["data"]

            text = data["selftext"]
            if text:
                text = textwrap.shorten(text, width=128, placeholder="...")
                text += "\n"  # Add newline to separate embed info

            ups = data["ups"]
            comments = data["num_comments"]
            author = data["author"]

            title = textwrap.shorten(data["title"],
                                     width=64,
                                     placeholder="...")
            link = self.URL + data["permalink"]

            embed.description += (
                f"[**{title}**]({link})\n"
                f"{text}"
                f"| {ups} upvotes | {comments} comments | u/{author} | {subreddit} |\n\n"
            )

        embed.colour = Colour.blurple()

        return await channel.send(content=content, embed=embed)
Esempio n. 10
0
 async def send_visualization(self,
                              ctx: BattleContext,
                              channel: discord.TextChannel = None) -> None:
     """Send battlefield visualization to the agent."""
     if self.user != None:
         if not self.user.bot:
             if not self.user.dm_channel:
                 await self.user.create_dm()
             channel = self.user.dm_channel
         if channel:
             with channel.typing():
                 with io.BytesIO() as data:
                     visualize_battle(ctx).save(data, 'PNG')
                     data.seek(0)
                     await channel.send(
                         file=discord.File(data, filename="battle.png"))
Esempio n. 11
0
 async def channelinfo(self, ctx, channel:discord.TextChannel=None):
     if channel == None:
         channel = ctx.channel
     async with channel.typing():
         em = discord.Embed(title = "Channel Info!", description = "Info about the channel", color = ctx.author.color)
         em.add_field(name = "Name", value = f"`{channel.name}`")
         em.add_field(name = "Mention", value = f"{channel.mention}")
         em.add_field(name = "Id", value = f"`{channel.id}`")
         em.add_field(name = "Category Id", value = f"`{channel.category_id}`")
         em.add_field(name = "Topic", value = f"`{channel.topic}`")
         em.add_field(name = "Slowmode", value = f"`{channel.slowmode_delay}`")
         em.add_field(name = "Position", value = f"`{channel.position}`")
         em.add_field(name = "Type", value = f"`{channel.type}`")
         em.add_field(name = "NSFW?", value = f"`{channel.is_nsfw()}`")
         em.add_field(name = "Announcments?", value = f"`{channel.is_news()}`")
         em.add_field(name = "Created At", value = f"`{channel.created_at}`")
         
         await ctx.send(embed = em)
Esempio n. 12
0
async def typing_loop(channel: TextChannel):
    """
    Global typing loop for the provided channel:
    Will run until the respective event is notified and
    there are no more typing terminals left.
    :param channel:
    :return:
    """
    if len(curr_typing[channel.id]) > 1:
        return

    typing_event[channel.id] = asyncio.Event()
    logger.info(f'Started typing in channel {channel.name}')
    async with channel.typing():
        await typing_event[channel.id].wait()
        while len(curr_typing[channel.id]) > 0:
            typing_event[channel.id].clear()
            await typing_event[channel.id].wait()
    logger.info(f'Stopped typing in channel {channel.name}')
    del typing_event[channel.id]
Esempio n. 13
0
async def post_cards(client: Client,
                     cards: List[Card],
                     channel: TextChannel,
                     replying_to: Optional[Member] = None,
                     additional_text: str = '') -> None:
    if len(cards) == 0:
        await post_no_cards(channel, replying_to)
        return
    not_pd = configuration.get_list('not_pd')
    disable_emoji = str(
        channel.id) in not_pd or (getattr(channel, 'guild', None) is not None
                                  and str(channel.guild.id) in not_pd)
    cards = uniqify_cards(cards)
    if len(cards) > MAX_CARDS_SHOWN:
        cards = cards[:DEFAULT_CARDS_SHOWN]
    if len(cards) == 1:
        text = single_card_text_internal(client, cards[0], disable_emoji)
    else:
        text = ', '.join('{name} {legal} {price}'.format(
            name=card.name,
            legal=((emoji.info_emoji(card)) if not disable_emoji else ''),
            price=((card_price.card_price_string(card, True)
                    ) if card.get('mode', None) == '$' else ''))
                         for card in cards)
    if len(cards) > MAX_CARDS_SHOWN:
        image_file = None
    else:
        with channel.typing():
            image_file = await image_fetcher.download_image_async(cards)
    if image_file is None:
        text += '\n\n'
        if len(cards) == 1:
            text += emoji.replace_emoji(cards[0].oracle_text, client)
        else:
            text += 'No image available.'
    text += additional_text
    if image_file is None:
        await send(channel, text)
    else:
        await send_image_with_retry(channel, image_file, text)
Esempio n. 14
0
    async def begin(self, member, channel: TextChannel):
        """
        Starts a a game in channel
        """
        table, delegate = await self.allowed_channel(channel)
        if table and table.is_playing:
            return await channel.send('Already playing craps!')
        playing = []
        player = await self.try_sit(member, table, channel)
        if player:
            playing.append(member)

        responses = await BeginGameScene().show(channel, self)
        for r in responses:
            if r.member in playing:
                continue
            player = await self.try_sit(r.member, table, channel)
            if player:
                playing.append(r.member)

        shooter = table.advance_button()
        shooter_member = None
        for p in playing:
            if p.id == shooter.id:
                shooter_member = p
                break
        if not shooter_member:
            raise CrapsException("No shooter!")

        player_str = 'Playing craps with: ' + ", ".join(
            [p.name for p in playing])
        sleep = 2.0 if not self.TEST_MODE else 0.5
        async with channel.typing():
            await asyncio.sleep(sleep)
            await channel.send(
                f'\n{T.bold(player_str)}\n'
                f"{shooter_member.mention} has the dice. Let's hope they're hot!\n"
            )
        await asyncio.sleep(sleep)
        await table.dealer.play(player.id)
Esempio n. 15
0
 async def say(self, ctx, channel: discord.TextChannel, *,
               message):  # p!say
     "Sends a message to a specified channel.\nThis command is only usable by staff members."
     if channel.id in arrays.CHANNELINFORMATION:
         info = arrays.CHANNELINFORMATION.get(channel.id)
         saySetting = info.get("Say")
         if not saySetting:
             return await ctx.send(
                 f"{ctx.author.mention}, you are not allowed to send messages to {channel.mention}."
             )
     async with channel.typing():
         characters = len(message)
         await asyncio.sleep(characters / 25)
     await channel.send(message,
                        allowed_mentions=discord.AllowedMentions(
                            everyone=True, roles=True, users=True))
     if channel != ctx.channel:
         embed = discord.Embed(color=0x80ff80)
         embed.add_field(name="Sent Message", value=message, inline=False)
         await ctx.send(
             f"{ctx.author.mention}, successfully sent the message to {channel.mention}.",
             embed=embed)
Esempio n. 16
0
    async def _queue(self, channel: discord.TextChannel, player_count: int):
        # Send Hint
        teams: list = ["🔴", "🔵"]
        async with channel.typing():
            team1, team2 = [], []
            max_pcount: int = player_count // 2
            emb = discord.Embed(title="⌛ Waiting for Other Player to Join...",
                                description=f"{max_pcount}v{max_pcount} mode",
                                colour=WHITE)
            emb.add_field(name="🔴 Red Team",
                          value="```Empty Room```",
                          inline=False)
            emb.add_field(name="🔵 Blue Team",
                          value="```Empty Room```",
                          inline=False)
            emb.set_footer(text="React to Join One of the Team 🔴 🔵")
        hm: discord.Message = await channel.send(embed=emb)
        for i in teams:
            await hm.add_reaction(i)

        # Edit Hint and Wait for User process
        try:
            while True:
                # Wait for Reaction Reply
                r, u = await self.bot.wait_for(
                    event="reaction_add",
                    timeout=60.0,
                    check=lambda reaction, user: True
                    if str(reaction.emoji
                           ) in teams and user.bot is False else False)

                # Check if user has already registered
                mbr_data = checkin_member(u)
                if mbr_data is not None:
                    if "PRIM-STAT" in mbr_data:
                        footer_text: str
                        if str(r.emoji) == "🔴":
                            if len(team1) == max_pcount:
                                footer_text = "Party Already Full"
                            else:
                                if u.id in [k.id for k in team1]:
                                    footer_text = f"🔴 {u.name}, You are already in this Team"
                                elif u.id in [k.id for k in team2]:
                                    indexRemove: int
                                    for omb in range(len(team2)):
                                        if team2[omb].id == u.id:
                                            indexRemove = omb
                                    obj = team2[indexRemove]
                                    team2.pop(indexRemove)
                                    team1.append(obj)
                                    footer_text = f"🔴 {u.name} Leave the Blue Team and Joined Red Team"
                                else:
                                    obj = checkClassID(u)
                                    team1.append(obj)
                                    footer_text = f"🔴 {u.name} Joined Red Team"
                        else:
                            if len(team2) == max_pcount:
                                footer_text = "Party Already Full"
                            else:
                                if u.id in [k.id for k in team1]:
                                    indexRemove: int
                                    for omb in range(len(team1)):
                                        if team1[omb].id == u.id:
                                            indexRemove = omb
                                    obj = team1[indexRemove]
                                    team1.pop(indexRemove)
                                    team2.append(obj)
                                    footer_text = f"🔵 {u.name} Leave the Red Team and Joined Blue Team"
                                elif u.id in [k.id for k in team2]:
                                    footer_text = f"🔵 {u.name}, You are already in this Team"
                                else:
                                    obj = checkClassID(u)
                                    team2.append(obj)
                                    footer_text = f"🔵 {u.name} Joined Blue Team"
                        await r.remove(u)
                        if len(team1) == max_pcount and len(
                                team2) == max_pcount:
                            break
                    else:
                        footer_text = f"{u.name} hasn't registered yet, type `{get_prefix(channel.guild)}start` to begin with RPG"

                    # Edit Hint Message
                    async with channel.typing():
                        emb = discord.Embed(
                            title="⌛ Waiting for Other Player to Join...",
                            description=f"{max_pcount}v{max_pcount} mode",
                            colour=WHITE)
                        emb.add_field(
                            name="🔴 Red Team",
                            inline=False,
                            value="\n".join([
                                f"> **{j.name}** ({j.ClassName})"
                                for j in team1
                            ]) if len(team1) > 0 else "```Empty Room```")
                        emb.add_field(
                            name="🔵 Blue Team",
                            inline=False,
                            value="\n".join([
                                f"> **{j.name}** ({j.ClassName})"
                                for j in team2
                            ]) if len(team2) > 0 else "```Empty Room```")
                        emb.set_footer(text=footer_text)
                    await hm.edit(embed=emb)

            # After it has been fulfiled, then let's Begin!
            await hm.delete()
            await self._lets_battle(channel, team1, team2)
        except asyncio.TimeoutError:
            await hm.delete(delay=1)
            await channel.send("*⚔️ Battle Canceled, Queue Timeout*")
            await self._cooling_down(channel.id)
Esempio n. 17
0
 async def make_info_channel(channel: TextChannel, content: AnyStr) -> Message:
     with channel.typing():
         await ChannelManager.purge_channel(channel)
         message: Message = await channel.send("WIP")
         await message.edit(content=content)
     return message
Esempio n. 18
0
    async def _lets_battle(self, channel: discord.TextChannel, t1: list,
                           t2: list):
        # Inner Functions
        # it Returns target attack, for default it will return None if not exist
        # Find Target Attack by Index
        def find_target_by_index(arg: int,
                                 target_team: list,
                                 *,
                                 move_sample: Movement = None,
                                 item_sample=None):
            """`team` must contains only `Character` object type."""
            if arg < 1 or arg > len(target_team):
                return None

            # Type Move use
            if move_sample is not None:
                # For Single Target, just return the target Character
                if move_sample.GetTargetID() == 1:
                    return target_team[arg - 1]

                # For Multiple Target
                else:
                    # Making sure the target is on the first index, then return a list of target
                    copy_team = target_team.copy()
                    list_target = [copy_team[arg - 1]]
                    del copy_team[arg - 1]
                    return list_target + copy_team

            return None

        # Find Target Attack by Name
        def find_target_by_name(arg: str,
                                target_team: list,
                                *,
                                move_sample: Movement = None,
                                item_sample=None):
            """`team` must contains only `Character` object type."""
            team_names = [n.name for n in target_team]
            if arg not in team_names:
                return None

            # Type Move use
            if move_sample is not None:
                # For Single Target, just return the target Character
                if move_sample.GetTargetID() == 1:
                    return team[team_names.index(arg)]

                # For Multiple Target
                else:
                    # Making sure the target is on the first index, then return a list of target
                    copy_team = target_team.copy()
                    list_target = [copy_team[team_names.index(arg)]]
                    del copy_team[team_names.index(arg)]
                    return list_target + copy_team

            return None

        def make_emb():
            nonlocal target
            emb = discord.Embed(
                title="⚔️ Arena ⚔️",
                description=f"**{turns[index][0].name}, Your Turn!**",
                colour=WHITE)
            emb.add_field(
                name=f"🔴 Red Team | Alive {survivet1}",
                inline=False,
                value="\n".join([
                    f"> {j + 1}. **{t1[j][0].name}** `HP: {t1[j][0].HP}/{t1[j][0].MAX_HP} | MANA: {t1[j][0].MANA}/{t1[j][0].MAX_MANA}`"
                    for j in range(len(t1))
                ]))
            emb.add_field(
                name=f"🔵 Blue Team | Alive {survivet2}",
                inline=False,
                value="\n".join([
                    f"> {j + 1}. **{t2[j][0].name}** `HP: {t2[j][0].HP}/{t2[j][0].MAX_HP} | MANA: {t2[j][0].MANA}/{t2[j][0].MAX_MANA}`"
                    for j in range(len(t2))
                ]))
            descr: str = ""
            if get_started is True:
                descr = "```Empty Log```"
            else:
                descr += f"`{char_turn[0].Msg}`\n"
                if isinstance(target, list):
                    for i in target:
                        descr += f"`{i.Msg}`"
                else:
                    descr += f"`{target.Msg}`"
            emb.add_field(name="📄 Battle Log", value=descr, inline=False)
            emb.set_footer(text="Send move Message in this channel.")
            return emb

        # Check user reply usage
        def check_reply(char: Character, your_team: list,
                        opposition_team: list):
            nonlocal target

            def inner_check(message: discord.Message):
                nonlocal target
                argument: list or tuple = message.content.split(' ')
                # 3 Argument beginning with "use" statement
                if argument[0].lower() == "use" and len(
                        argument) == 3 and message.author.id == char.id:
                    # Specify what do player want to do
                    # Using a normal move from Character
                    if argument[1].lower() == "normal":
                        if is_number(argument[2]):
                            target = find_target_by_index(
                                int(argument[2]),
                                opposition_team,
                                move_sample=char._normal_move)
                        else:
                            target = find_target_by_name(
                                argument[2],
                                opposition_team,
                                move_sample=char._normal_move)

                        # Use Character Normal Move
                        if target is not None:
                            char.NormalAttack(target)
                            return True

                    # Using a custom move from Character
                    elif is_number(argument[1]):
                        if int(argument[1]) >= 1 or int(argument[1]) <= len(
                                char._custom_moves):
                            if is_number(argument[2]):
                                target = find_target_by_index(
                                    int(argument[2]),
                                    opposition_team,
                                    move_sample=char._normal_move)
                            else:
                                target = find_target_by_name(
                                    argument[2],
                                    opposition_team,
                                    move_sample=char._normal_move)

                            # Use Character Normal Move
                            if target is not None:
                                char.CustomAttack(target, int(argument[1]))
                                return True

                    # Using a item from Character
                    # elif (argument[1] in moves or argument[1] in items) and (is_number(argument[2]) or argument[2] in names_in_game):
                    #     return True
                return False

            return inner_check

        # Initialize Attribute
        turns: list = []
        get_started: bool = True
        send_count, index = 0, 0
        survivet1: int = len(t1)
        survivet2: int = len(t2)
        char_turn = None
        target = None

        # Preparing Turns and Teams
        async with channel.typing():
            # For Team 1 (Red Team)
            for i in t1:
                while index < len(turns):
                    if i.SPD > turns[index][0].SPD:
                        break
                    index += 1
                turns.insert(index, (i, 1))  # 1 means the team id for Red Team
                index = 0

            # For Team 2 (Blue Team)
            for j in t2:
                while index < len(turns):
                    if j.SPD > turns[index][0].SPD:
                        break
                    index += 1
                turns.insert(index,
                             (j, 2))  # 2 means the team id for Blue Team
                index = 0

            # Send Hint to all PPL and Channel
            for k in turns:
                char_user: discord.User = self.bot.get_user(k[0].id)
                await send_batte_hint(char_user, k[0])
            t1 = [(turns[c1][0], c1) for c1 in range(len(turns))
                  if turns[c1][1] == 1]
            t2 = [(turns[c2][0], c2) for c2 in range(len(turns))
                  if turns[c2][1] == 2]
        hm: discord.Message = await channel.send(embed=make_emb())

        # Game ON!
        try:
            while True:
                # Waiting for user to input action
                # Turn Character, then user need to send action
                char_turn = turns[index]
                if char_turn[0].HP == 0:
                    index = (index + 1) if index < len(turns) - 1 else 0
                    continue

                # Character from Red Team
                reply: discord.Message = None
                if char_turn[1] == 1:
                    reply = await self.bot.wait_for(
                        event="message",
                        timeout=60.0,
                        check=check_reply(char_turn[0], [i[0] for i in t1],
                                          [j[0] for j in t2]))
                # Character from Blue Team
                else:
                    reply = await self.bot.wait_for(
                        event="message",
                        timeout=60.0,
                        check=check_reply(char_turn[0], [i[0] for i in t2],
                                          [j[0] for j in t1]))
                await reply.delete()

                async with channel.typing():
                    # Check Team Completion
                    survivet1 = 0
                    survivet2 = 0
                    for pt1 in t1:
                        if pt1[0].HP > 0:
                            survivet1 += 1
                    for pt2 in t2:
                        if pt2[0].HP > 0:
                            survivet2 += 1
                    if survivet1 == 0 or survivet2 == 0:
                        break

                # Edit Hint, Resend Battle Message
                get_started = False
                index = (index + 1) if index < len(turns) - 1 else 0
                send_count = (send_count + 1) if send_count < 2 else 0
                if send_count == 0:
                    await hm.delete()
                    hm = await channel.send(embed=make_emb())
                else:
                    await hm.edit(embed=make_emb())

            # Send Reward
            gld_data = checkin_guild(channel.guild)
            event_channel: discord.TextChannel = self.bot.get_channel(
                int(gld_data["event-channel"])
            ) if gld_data["event-channel"] is not None else channel
            if survivet1 <= 0:
                for i in t2:
                    char_user = self.bot.get_user(i[0].id)
                    await add_exp(event_channel, char_user, RewardEXP)
                    await add_money(channel.guild.id, char_user, RewardMoney)
                for i in t1:
                    char_user = self.bot.get_user(i[0].id)
                    await add_exp(
                        event_channel, char_user,
                        math.ceil(RewardEXP - (RewardEXP * (80 / 100))))
                    await add_money(
                        channel.guild.id, char_user,
                        math.ceil(RewardMoney - (RewardMoney * (80 / 100))))
                emb = discord.Embed(
                    title="🔵 Blue Team Wins!",
                    colour=WHITE,
                    description="\n".join(
                        [f"> {winner[0].name}" for winner in t2]),
                )
                emb.add_field(
                    name="Reward :",
                    inline=False,
                    value=
                    f"EXP: {RewardEXP} | Money: {RewardMoney} {checkin_guild(channel.guild)['currency']['type']}"
                )
                await channel.send(embed=emb)
            else:
                for i in t1:
                    char_user = self.bot.get_user(i[0].id)
                    await add_exp(event_channel, char_user, RewardEXP)
                    await add_money(channel.guild.id, char_user, RewardMoney)
                for i in t2:
                    char_user = self.bot.get_user(i[0].id)
                    await add_exp(
                        event_channel, char_user,
                        math.ceil(RewardEXP - (RewardEXP * (80 / 100))))
                    await add_money(
                        channel.guild.id, char_user,
                        math.ceil(RewardMoney - (RewardMoney * (80 / 100))))
                emb = discord.Embed(title="🔴 Red Team Wins!",
                                    description="\n".join([
                                        f"> {winner[0].name}" for winner in t1
                                    ]),
                                    colour=WHITE)
                emb.add_field(
                    name="Reward :",
                    inline=False,
                    value=
                    f"EXP: {RewardEXP} | Money: {RewardMoney} {checkin_guild(channel.guild)['currency']['type']}"
                )
                await channel.send(embed=emb)
            # Delete Cooldown
            await self._cooling_down(channel.channel.id)
        except asyncio.TimeoutError:
            await hm.delete(delay=1)
            await channel.send(
                f"*Gameplay turn Timeout! {char_turn[0].name}, where have you been?*"
            )
            await self._cooling_down(channel.id)
Esempio n. 19
0
    async def now(self, ctx, source: discord.Member = None, channel: discord.TextChannel = None):
        """Enregistre les messages d'un membre sur un salon à partir de maintenant

        Pour arrêter, le conteur doit dire "stop" (sans rien d'autre)
        - Si le <teller> n'est pas spécifié, c'est celui qui fait la commande qui l'est
        - Si le salon n'est pas spécifié, c'est celui où est réalisé la commande"""
        if not source: source = ctx.author
        if not channel: channel = ctx.channel
        em_color = await ctx.embed_color()

        path = str(self.temp)
        filepath = path + "/{1}_{0}.txt".format(source.name, datetime.now().strftime("%Y%m%d%H%M"))
        nb = 0
        pre_txt = "| Auteur = {}\n" \
              "| Salon = #{}\n" \
              "| Date de début = {}\n\n".format(str(source), channel.name, datetime.now().strftime("%d/%m/%Y %H:%M"))
        txt = ""

        def check(m: discord.Message):
            return m.author == source and m.channel == channel

        async def write(txt: str):
            file = open(filepath, "w")
            file.write(txt)
            file.close()
            return file

        async def post_all(txt: str):
            if len(txt) < 10000:
                chunks = txt.split("\n")
                page = 1
                post = pre_txt
                for chunk in chunks:
                    if len(chunk) + len(post) < 1950:
                        post += chunk + "\n"
                    else:
                        em = discord.Embed(description=post, color=em_color)
                        em.set_footer(text=f"Page #{page}")
                        await channel.send(embed=em)
                        post = chunk + "\n"
                        page += 1
                if post:
                    em = discord.Embed(description=post, color=em_color)
                    em.set_footer(text=f"Page #{page}")
                    await channel.send(embed=em)

        em = discord.Embed(description=f"🔴 **Début de l'enregistrement**\n"
                                       f"Pour arrêter l'enregistrement, {source.mention} doit dire \"stop\".\n"
                                       f"L'enregistrement s'arrête seul si le conteur ne dit rien pendant plus de 5 min ou si l'histoire dépasse 20 000 caractères.\n",
                           color=em_color)
        debut = await channel.send(embed=em)

        while True:
            try:
                msg = await self.bot.wait_for("message", check=check, timeout=300)
            except asyncio.TimeoutError:
                em = discord.Embed(description="🔴 **Fin auto. de l'enregistrement**\n"
                                               "Aucun message n'a été écrit depuis 5 min.", color=em_color)
                em.set_footer(text="Veuillez patienter pendant la génération du fichier .txt")
                await channel.send(embed=em, delete_after=20)
                try:
                    async with channel.typing():
                        await post_all(txt)
                        await write(pre_txt + txt)
                    await channel.send(files=[discord.File(filepath)])
                    os.remove(filepath)
                except:
                    await channel.send("**Erreur** • Je n'ai pas réussi à upload le fichier...")
                await debut.delete()
                return
            else:
                if msg.content:
                    if msg.content.lower() == "stop" or len(txt) >= 20000:
                        em = discord.Embed(description="🔴 **Fin de l'enregistrement**\n"
                                                       "Il y a eu {} messages enregistrés.".format(nb), color=em_color)
                        em.set_footer(text="Veuillez patienter pendant la génération du fichier .txt")
                        await channel.send(embed=em, delete_after=20)
                        try:
                            async with channel.typing():
                                await post_all(txt)
                                await write(pre_txt + txt)
                            await channel.send(files=[discord.File(filepath)])
                            os.remove(filepath)
                        except:
                            await channel.send("**Erreur** • Je n'ai pas réussi à upload le fichier...")
                        await debut.delete()
                        return
                    else:
                        txt += msg.content + "\n"
                        nb += 1
Esempio n. 20
0
 async def infinitetyping(self, ctx, channel: discord.TextChannel):
     print("Excessively long typing begins.")
     async with channel.typing():
         await asyncio.sleep(100000)
         await ctx.send(f"Finished annoying people in {channel.name}.")
         print("Finished long typing.")
Esempio n. 21
0
    async def report_members(self,
                             member_list,
                             channel: discord.TextChannel,
                             caller: discord.Member,
                             mentions=False):
        """
        Helper function that takes a member list and reports it back to a member in a specified channel.
        :param member_list:
        :param channel:
        :param caller:
        :param mentions: if False, show the display name and username; if True, list mentions.
        :return:
        """
        num_members = len(member_list)

        member_count_str = f"{caller.mention}: {num_members} members"
        await channel.send(member_count_str)
        if num_members == 0:
            return

        member_list_str = self.member_list_entry(member_list[0],
                                                 mentions=mentions)
        for member in member_list[1:]:
            member_list_str += "\n" + self.member_list_entry(member,
                                                             mentions=mentions)

        message_length = 2000
        messages_to_send = []
        if len(member_list_str) <= message_length:
            messages_to_send = [member_list_str]
        else:
            curr_message = ""
            for line in member_list_str.splitlines(keepends=True):
                if len(curr_message) + len(line) > message_length:
                    messages_to_send.append(curr_message)
                    curr_message = line
                else:
                    curr_message += line
            messages_to_send.append(curr_message)

        for i, message_text in enumerate(messages_to_send):
            async with channel.typing():
                await channel.send(message_text)
                if i + 1 < len(messages_to_send):
                    await channel.send(
                        f"Show more members (y/n)?  Will cancel in {self.timeout} seconds."
                    )

                    def check(m):
                        if m.author != caller:
                            return False
                        elif m.content.lower() in ("y", "n", "yes", "no"):
                            return True

                    cancel_listing = False
                    try:
                        msg = await self.bot.wait_for("message",
                                                      check=check,
                                                      timeout=self.timeout)
                        if msg.content.lower() not in ("y", "yes"):
                            cancel_listing = True
                    except asyncio.TimeoutError:
                        cancel_listing = True

                    if cancel_listing:
                        async with channel.typing():
                            await channel.send(f"Cancelled.")
                        return