Esempio n. 1
0
    async def on_member_remove(self, member):
        print(f'{member} has left a server')

        ch = discord.TextChannel(position=0)
        print(channel_list)
        await ch.send(
            f'Retard has been just kicked. I hope u will die {member}')
Esempio n. 2
0
def make_settings():
    data = dict({
        "id": 1,
        "type": ChannelType.text,
        "name": "name",
        "position": 0,
        "attachments": [],
        "embeds": [],
        "edited_timestamp": None,
        "pinned": False,
        "mention_everyone": False,
        "tts": None,
        "content": "not true content: error",
        "nonce": None,
        "stickers": []
    })
    state = ConnectionState(
        dispatch=None,
        handlers=None,
        hooks=None,
        syncer=None,
        http=None,
        loop=None
    )

    channel = discord.TextChannel(state=state,
                                  guild=discord.Guild(
                                      data=data,
                                      state=state
                                  ),
                                  data=data)
    return state, data, channel
Esempio n. 3
0
async def on_member_join(member):
    welcome = 748697685871296592
    channel = discord.TextChannel(guild=welcome, state=None, data=None)
    embed = discord.Embed(
        title=f' Test subject {member} has joined a server.',
        description=
        "Your role will be set to verified automatically in 5 minutes.",
        color=discord.Colour.green())

    print(embed=embed)

    asyncio.sleep(300)

    ROLE = 748701878388523059

    role = get(member.guild.roles, name=ROLE)

    async with channel.typing():

        await member.add_roles(role)
        embed2 = discord.Embed(
            title=f"{member} was given {role}",
            description=
            "If you have time to provide feedback to improve the bot that would be well appreciated!",
            color=discord.Colour.blue())

        print(embed=embed2)
Esempio n. 4
0
def read_chat(path):
    meta = json.load(open(path + '.meta.json'))
    if 'channel' not in meta:
        raise ValueError("Not a channel log")

    channel_id = meta['channel']['id']
    channel_name = meta['channel']['name']

    print(f"Channel {channel_name} (id {channel_id})")

    # Create a crippled state
    # TODO implement our own
    state = discord.state.ConnectionState.__new__(
        discord.state.ConnectionState)
    state.max_messages = 1000
    state.http = None
    state.clear()

    # Mock a guild
    # TODO restore from run data
    guild = discord.Guild.__new__(discord.Guild)
    guild.id = 0
    guild._members = {}
    guild._roles = {}
    guild.name = ''

    channel = discord.TextChannel(state=state,
                                  guild=guild,
                                  data={
                                      'id': channel_id,
                                      'type': 0,
                                      'name': channel_name,
                                      'parent_id': 0,
                                      'position': 0
                                  })

    if os.path.exists(path + '.jsonl.gz'):
        file = gzip.open(path + '.jsonl.gz')
    else:
        file = open(path + '.jsonl')

    for line in file:
        line = json.loads(line)
        if line['type'] != 'http':
            continue

        if line['request']['url'].endswith(f'/channels/{channel_id}/messages'):
            for message_data in reversed(line['response']['data']):
                message = discord.Message(state=state,
                                          channel=channel,
                                          data=message_data)
                if message.type == discord.MessageType.default:
                    print(
                        f"[{message.created_at}] <{message.author}> {message.content}"
                    )
                else:
                    print(f"[{message.created_at}] {message.system_content}")
Esempio n. 5
0
 def _handle_option_channel(self, data: dict, option: ResponseOption,
                            resolved: Dict[str, Dict[str, dict]]):
     channel_id = int(data["value"])
     resolved_channel = resolved["channels"][data["value"]]
     if self.guild_id:
         if channel := self.guild.get_channel(channel_id):
             pass
         else:
             channel = discord.TextChannel(state=self._state,
                                           guild=self.guild,
                                           data=resolved_channel)
Esempio n. 6
0
 async def fetch_channel(self, cid):
     """
     Fetches and caches a user.
     :type cid: int
     :rtype: None or discord.TextChannel
     """
     result = None
     data = await self.get_object_doc('channel', cid)
     if data:
         gdat = await self.get_object_doc('guild', data['guild_id'])
         if gdat:
             result = discord.TextChannel(state=self.state,
                                          guild=gdat,
                                          data=data)
     return result
Esempio n. 7
0
 async def create_thread(self, message, name, auto_archive_duration=1440):
     channel = message.channel
     data = await message.guild._state.http.request(
         discord.http.Route(
             "POST",
             "/channels/{channel_id}/messages/{message_id}/threads",
             channel_id=channel.id,
             message_id=message.id),
         json={
             "name": name,
             "auto_archive_duration": auto_archive_duration
         })
     data["position"] = 100
     channel = discord.TextChannel(state=message.guild._state,
                                   guild=message.guild,
                                   data=data)
     return channel
Esempio n. 8
0
# Create a TextChannel instance to get a realistic MagicMock of `discord.TextChannel`
channel_data = {
    'id': 1,
    'type': 'TextChannel',
    'name': 'channel',
    'parent_id': 1234567890,
    'topic': 'topic',
    'position': 1,
    'nsfw': False,
    'last_message_id': 1,
}
state = unittest.mock.MagicMock()
guild = unittest.mock.MagicMock()
channel_instance = discord.TextChannel(state=state,
                                       guild=guild,
                                       data=channel_data)


class MockTextChannel(CustomMockMixin, unittest.mock.Mock, HashableMixin):
    """
    A MagicMock subclass to mock TextChannel objects.

    Instances of this class will follow the specifications of `discord.TextChannel` instances. For
    more information, see the `MockGuild` docstring.
    """
    spec_set = channel_instance

    def __init__(self, **kwargs) -> None:
        default_kwargs = {
            'id': next(self.discord_id),
Esempio n. 9
0
    async def test_server_info_command(self, time_since_patch):
        time_since_patch.return_value = '2 days ago'

        self.ctx.guild = helpers.MockGuild(
            features=('lemons', 'apples'),
            region="The Moon",
            roles=[self.moderator_role],
            channels=[
                discord.TextChannel(
                    state={},
                    guild=self.ctx.guild,
                    data={'id': 42, 'name': 'lemons-offering', 'position': 22, 'type': 'text'}
                ),
                discord.CategoryChannel(
                    state={},
                    guild=self.ctx.guild,
                    data={'id': 5125, 'name': 'the-lemon-collection', 'position': 22, 'type': 'category'}
                ),
                discord.VoiceChannel(
                    state={},
                    guild=self.ctx.guild,
                    data={'id': 15290, 'name': 'listen-to-lemon', 'position': 22, 'type': 'voice'}
                )
            ],
            members=[
                *(helpers.MockMember(status=discord.Status.online) for _ in range(2)),
                *(helpers.MockMember(status=discord.Status.idle) for _ in range(1)),
                *(helpers.MockMember(status=discord.Status.dnd) for _ in range(4)),
                *(helpers.MockMember(status=discord.Status.offline) for _ in range(3)),
            ],
            member_count=1_234,
            icon_url='a-lemon.jpg',
        )

        self.assertIsNone(await self.cog.server_info(self.cog, self.ctx))

        time_since_patch.assert_called_once_with(self.ctx.guild.created_at, precision='days')
        _, kwargs = self.ctx.send.call_args
        embed = kwargs.pop('embed')
        self.assertEqual(embed.colour, discord.Colour.blurple())
        self.assertEqual(
            embed.description,
            textwrap.dedent(
                f"""
                **Server information**
                Created: {time_since_patch.return_value}
                Voice region: {self.ctx.guild.region}
                Features: {', '.join(self.ctx.guild.features)}

                **Channel counts**
                Category channels: 1
                Text channels: 1
                Voice channels: 1
                Staff channels: 0

                **Member counts**
                Members: {self.ctx.guild.member_count:,}
                Staff members: 0
                Roles: {len(self.ctx.guild.roles)}

                **Member statuses**
                {constants.Emojis.status_online} 2
                {constants.Emojis.status_idle} 1
                {constants.Emojis.status_dnd} 4
                {constants.Emojis.status_offline} 3
                """
            )
        )
        self.assertEqual(embed.thumbnail.url, 'a-lemon.jpg')
Esempio n. 10
0
                             'bot': True,
                             'avatar': None
                         })

# We cannot instantiate the Guild class directly because we have no state object,
# but we barely need it for anything so let's get around that
TEST_GUILD = discord.Guild.__new__(discord.Guild)
TEST_GUILD.id = 805808489695150180
TEST_GUILD.name = "Discard Test Server"
TEST_GUILD._members = {}

TEST_CHANNEL = discord.TextChannel(state=None,
                                   guild=TEST_GUILD,
                                   data={
                                       'id': 805808489695150183,
                                       'type': 0,
                                       'name': 'general',
                                       'parent_id': 0,
                                       'position': 0
                                   })

TEST_CHANNEL2 = discord.TextChannel(state=None,
                                    guild=TEST_GUILD,
                                    data={
                                        'id': 805808821749415946,
                                        'type': 0,
                                        'name': 'test',
                                        'parent_id': 0,
                                        'position': 1
                                    })
Esempio n. 11
0
 async def on_member_join(self, member):
     print(f'{member} has joind a server.')
     ch = discord.TextChannel(position=0)
     print(channel_list)
     await ch.send(
         f'Retard has just joined us. I wish u pleasent dying {member}')
Esempio n. 12
0
                                                          spec_set=True)


# Create a `discord.TextChannel` instance
channel_data = {
    'id': 1,
    'type': 'TextChannel',
    'name': 'channel',
    'parent_id': 657571218324586497,
    'topic': 'topic',
    'position': 1,
    'nsfw': False,
    'last_message_id': 1,
}
channel_instance = discord.TextChannel(state=unittest.mock.MagicMock(),
                                       guild=unittest.mock.MagicMock(),
                                       data=channel_data)


class MockTextChannel(unittest.mock.AsyncMock):
    """A mock subclass to mock `discord.TextChannel` objects."""
    spec_set = channel_instance


# Create a `discord.ext.commands.Context` instance
context_instance = Context(message=unittest.mock.MagicMock(),
                           prefix=unittest.mock.MagicMock())


class MockContext(unittest.mock.Mock):
    """A mock subclass to mock `discord.ext.commands.Context` objects."""
Esempio n. 13
0
 async def load_channels(self, load_message=True):
     async with self.load_channels_lock:
         if load_message:
             print(
                 'Loading feed services... This could take some time depending on the number of feeds.'
             )
         start = datetime.datetime.utcnow()
         existing_ids = await self._discord_client.loop.run_in_executor(
             None, self.get_channel_ids_with_feeds)
         get_channel_tasks = []
         try:
             if existing_ids is not None:
                 for channel_id_with_feed in existing_ids:
                     if self.service.cli_args.startup_debug:  # mock a channel and change it to a valid id to test load
                         c_data = {
                             "id": channel_id_with_feed,
                             "type": None,
                             "name": "Startup DEBUG Feed",
                             "position": 1
                         }
                         first_guild = self._discord_client.guilds[
                             0]  # pick out the first guild in the list for state population
                         channel_obj = discord.TextChannel(
                             state=None, data=c_data, guild=first_guild)
                         get_channel_tasks.append(
                             self.get_channel_feed(channel_obj))
                     else:
                         channel_obj = self._discord_client.get_channel(
                             channel_id_with_feed)
                         if channel_obj is not None:
                             get_channel_tasks.append(
                                 self.get_channel_feed(channel_obj))
             else:
                 async for i in self.__get_text_channels():
                     get_channel_tasks.append(self.get_channel_feed(i))
         except Exception as ex:
             traceback.print_exc()
             print(ex)
         ratio_print = .25
         loaded_count = 0
         total_load = len(get_channel_tasks)
         if len(get_channel_tasks) > 0:
             if load_message:
                 print("Started loading {} feeds.".format(total_load))
             for f in asyncio.as_completed(get_channel_tasks):
                 loaded_count += 1
                 try:
                     await f
                 except Exception as ex:
                     traceback.print_exc()
                     print(
                         "Error when loading a channel feed: Ex: {}".format(
                             ex))
                 if load_message:
                     if loaded_count > (total_load * ratio_print):
                         print("Loaded {} feeds of {}. {}% done".format(
                             loaded_count, total_load,
                             int(ratio_print * 100)))
                         ratio_print += .25
             if load_message:
                 print("Loaded {} feeds in {:.1f} seconds".format(
                     len(get_channel_tasks),
                     (datetime.datetime.utcnow() - start).total_seconds()))