コード例 #1
0
async def on_ready():
    '''
    Message cache etc. is ready
    '''
    rebuild_server_cfgs([guild for guild in bot.guilds if guild.id != RELAY_ID])
    await relay_startup(bot)

    logger.info("Server List:\n" +
                "\n".join(
                    f"\t{server.name} "
                    f"({len(server.members)} members)"
                    for server in bot.guilds))

    logger.info(f"Startup completed in {round(get_uptime(),3)}s")

    for guild in bot.guilds:
        if guild.id != int(
                cfg["Hosting"]["relay-id"]) and sum_of_weights(guild) == 0:
            await rebuild_weight_table(guild)

    if cfg["Settings"]["notify-on-startup"] == "True":
        owner = (await bot.application_info()).owner
        await owner.send("Bot is online.")

    # startup notify
    try:
        with open("restart.cfg", "r") as f:
            channel_id = int(f.read())
            if channel := bot.get_channel(channel_id):
                await channel.send(f"Restart completed. Version is: {version}")
            elif user := bot.get_user(channel_id):
                await user.send(f"Restart completed. Version is: {version}")
コード例 #2
0
ファイル: foxxo.py プロジェクト: ntoskrnl4/arbys
async def initialize():
	global foxxo_channel, foxxo_channel_cache, wolfie_channel, wolfie_channel_cache, doggo_channel, doggo_channel_cache, raccoon_channel, raccoon_channel_cache
	foxxo_channel = client.get_channel(526155899295891456)
	foxxo_channel_cache = []
	
	wolfie_channel = client.get_channel(565247287534682112)
	wolfie_channel_cache = []
	
	doggo_channel = client.get_channel(564533446504873986)
	doggo_channel_cache = []
	
	raccoon_channel = client.get_channel(563314782141153321)
	raccoon_channel_cache = []
コード例 #3
0
async def on_member_join(member):
    ch = client.get_channel(GREETING_CHANNEL)

    new_user_message = "New member " + member.name + " has joined the channel."
    print(member)

    await ch.send(new_user_message)

    user_email = await get_user_email_and_id(member)

    if user_email:
        await submit_details(user_email,member)
        print('sending')

    ch =  client.get_channel(MENTOR_CHANNEL)
    
    url = 'http://127.0.0.1:3000/api/v1/users'
    headers = {
        'Content-Type': 'application/vnd.api+json'
    }
    myobj = {
        "data": {
          "attributes":{
            "email": str(member.id)+ "@gmail.com",
            "name": "discord"+member.name,
            "discord_id": str(member.id),
            "username": member.name,
            "password": "******",
            "buddy":0
          },
          "type":"users"
        }
    }

    resp = requests.request("POST", url, headers=headers, json=myobj)
    resp = resp.json()

    user_discord_id = resp["data"]["attributes"]["discord_id"]
    mentor_discord_id = resp["data"]["attributes"]["mentor_discord_id"]


    user = await client.fetch_user(int(user_discord_id)) 
    mentor = await client.fetch_user(int(mentor_discord_id))

    user_msg = 'Your mentor is: {0.mention}'.format(mentor)
    mentor_msg = 'Your nmentee is: {0.mention}'.format(user)

    await user.send(user_msg)
    await mentor.send(mentor_msg)
コード例 #4
0
def get_target_voice_connection(object: Union[discord.Member, discord.Guild, discord.VoiceChannel, int]) -> Union[discord.VoiceClient, MusicException]:
	target = None

	if isinstance(object, discord.Member):
		target = getattr(object.voice, "channel", None)
	if isinstance(object, discord.Guild):
		target = getattr(discord.utils.find(lambda x: x.guild.id == object.id, client.voice_clients), "channel", None)
	if isinstance(object, discord.VoiceChannel):
		target = object

	if isinstance(object, int):
		# seriously :/
		log.warning("get_target_voice_channel() given a raw integer/ID; this probably should not happen but I'll try my best")

		channel = client.get_channel(object)
		guild = client.get_guild(object)
		if isinstance(guild, discord.Guild):
			target = discord.utils.find(lambda x: x.id == object, client.voice_clients).channel

		elif isinstance(channel, discord.VoiceChannel):
			target = channel

		else:
			target = None

	if not isinstance(target, discord.VoiceChannel):
		return None
	# now we know that target is a VoiceChannel
	if not check_if_user_in_channel(target, client.user.id):
		# if we're not in the channel
		return NotConnectedException("We're not currently connected to this voice channel")
	else:
		return discord.utils.find(lambda x: x.channel.id == target.id, client.voice_clients)
コード例 #5
0
ファイル: .py プロジェクト: GilbertzRivi/smokel
async def loop_10m():
    now = datetime.now().timestamp()
    json_file = loads(read('events.json'))
    events = json_file['all']['events']
    for event in events:
        print(now, float(event), now > float(event))
        if now > float(event):
            temp = 0
            chan = client.get_channel(events[event]['cid'])
            msg = await chan.fetch_message(events[event]['mid'])
            opis = events[event]['desc']
            embed = Embed(title='Przypominajka o evencie!',
                          timestamp=datetime.utcnow())
            embed.add_field(name=opis.split(' /// ')[0],
                            value=' '.join(opis.split(' /// ')[1:]))
            react_num = len(msg.reactions)
            for react in msg.reactions:
                async for user in react.users(limit=None, after=None):
                    if user == client.user: continue
                    try:
                        await user.send(embed=embed)
                        temp += 1
                    except:
                        pass
            json_rem('events.json', ['all', 'events', event])
        await vrb.host.send(
            f'Wysłano wiadomości przypominające do {temp} osób, zareagowało {react_num} osób\n**Nie zapomnij pousuwać 3 części kodu z tej komendy po przeprowadzeniu testu!**'
        )
コード例 #6
0
async def on_raw_reaction_remove(payload):

    json_file = loads(read('config.json'))
    single_roles_orientations = json_file['autoroles'][
        'single_roles_orientations']

    guild = client.get_guild(payload.guild_id)
    channel = client.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    member = guild.get_member(payload.user_id)

    if not channel == vrb.autoroles_chan1 and not channel == vrb.autoroles_chan2 or member == client.user:
        return
    if len(message.content.split('\n')) > 1:
        role_name = message.content.split('\n')[-1].split(' - ')[0][2:-2]
    elif len(message.embeds) == 0:
        role_name = message.content.split(' - ')[0][2:-2]
    else:
        role_name = message.embeds[0].fields[0].name
    role = get(guild.roles, name=role_name)

    await member.remove_roles(role)

    if role.id in single_roles_orientations and not chk_list_cohesion(
        [role.id for role in member.roles], single_roles_orientations):
        await member.add_roles(vrb.nie_zarucham)
コード例 #7
0
ファイル: message_delete.py プロジェクト: GilbertzRivi/smokel
async def on_bulk_message_delete(messages):
    attachments_saveing_channel = client.get_channel(555876098819227649)
    for message in messages:    
        if message.channel.id == 559910981392793601: return
        e = Embed(colour=message.author.color, timestamp=datetime.utcnow())
        e.set_author(name=f"Wiadomosc usunięta")
        e.add_field(name='Kanał', value=message.channel, inline=False)
        if len(message.content) > 0:
            e.add_field(name='Treść', value=message.content, inline=False)
        else:
            e.add_field(name='Treść', value='Brak zawartości', inline=False)
        e.set_footer(text=f'{message.author.name} {message.author.id}', icon_url=message.author.avatar_url)
        try:
            await vrb.logs_chan.send(embed=e)
        except: pass
        if len(message.attachments) > 0:
            await vrb.logs_chan.send('Załączniki załączone do wiadomości')
            for a in message.attachments:
                await a.save(fp=a.filename, use_cached=True)
                saveing_file = discord_file(a.filename, a.filename, False)
                saveing_msg = await attachments_saveing_channel.send(file=saveing_file)
                a_url = saveing_msg.attachments[0].url
                ea = Embed(colour=vrb.host.colour, timestamp=datetime.utcnow())
                ea.set_footer(text=f'{message.author.name} {message.author.id}', icon_url=message.author.avatar_url)
                ea.set_author(name='Pliki załączone do wiadomości')
                ea.set_image(url=a_url)
                await vrb.logs_chan.send(embed=ea)
                remove(a.filename)
コード例 #8
0
ファイル: markov.py プロジェクト: SuperTails/discord-awoobot
async def markov(command: str, message: discord.Message):
    command = command.split(" ")
    try:
        command[1]
    except IndexError:
        c = message.channel
    else:
        try:
            c = client.get_channel(_common.stripMentionsToID(command[1]))
            if c is None:
                await message.channel.send(
                    "Unknown channel - I may not be in that channel's server")
        except ValueError:
            await message.channel.send(
                "First argument to command `markov` must be a channel mention")
            return

    async with message.channel.typing():
        msg_hist = await c.history(limit=3000).flatten()
        msg_hist_content = [x.clean_content for x in msg_hist]
        src_str = "\n".join(msg_hist_content)
        model = markovify.NewlineText(src_str)
        for _ in range(10):
            ret = model.make_short_sentence(500)
            if ret is not None:
                break
        else:
            ret = "<Error: For some reason the chain did not generate an acceptable sentence. Please rerun the command.>"
    await message.channel.send(ret)
    return
コード例 #9
0
ファイル: gbu.py プロジェクト: NOOBUV/discord-bot
async def called_once_a_week_gbu():
    message_channel = client.get_channel(int(os.environ['GBU_CHANNEL']))

    tasks = [
        asyncio.create_task(get_user_gbu(message_channel, member))
        for member in message_channel.members if member.bot ==False
    ]
    await asyncio.wait(tasks)
コード例 #10
0
async def new_member_joined(member, GREETING_CHANNEL):
  ch = client.get_channel(GREETING_CHANNEL)

  new_user_message = "New member " + member.name + " has joined the channel. Please everyone welcome " + member.name

  user_prompt = get_user_joined_prompt()
  user_prompt.add_field(name=" Welcome ", value= new_user_message, inline=False)
  asyncio.ensure_future(ch.send(embed= user_prompt))

  user_email = "*****@*****.**"         #temporarily
  resp = await submit_user_details(member, user_email)
  return resp
コード例 #11
0
async def called_once_a_week():
    message_channel = client.get_channel(GBU_CHANNEL)
    print(f"Got channel {message_channel}")
    # loop = asyncio.get_running_loop()
    # loop.close()
    tasks = []

    loop = asyncio.get_event_loop()
    tasks = [
        loop.create_task(get_user_gbu(message_channel, member))
        for member in message_channel.members if member.bot == False
    ]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
コード例 #12
0
async def command(command: str, msg: discord.Message):
    a1 = command.split(" ", 2)
    ch_idstr = a1[1]
    text = a1[2]

    daddyid = int(ch_idstr)

    channel = client.get_channel(daddyid)

    if channel is not None:  # and msg.author.id(195582200270290944):
        await channel.send(text)
    else:
        raise TypeError(
            "Invalid or non-existant channel ID (Not a text channel? Vars are",
            daddyid, text)
コード例 #13
0
ファイル: markov.py プロジェクト: bruceyang1998/arbys
async def command(command: str, message: discord.Message):
	command = command.split(" ")
	try:
		command[1]
	except IndexError:
		c = message.channel
	else:
		try:
			c = client.get_channel(__common__.stripMentionsToID(command[1]))
		except:
			c = message.channel
			pass

	try:
		a = client.get_user(__common__.stripMentionsToID(command[1]))
		if a is not None:
			target_user_id = a.id
		else:
			target_user_id = None
	except:
		target_user_id = None

	async with message.channel.typing():
		if "src=cache" in command:
			msg_hist = list(client._connection._messages)
			await message.channel.send(f"[Generating markov chain from {len(client._connection._messages)} messages in cache...]")
		elif target_user_id is not None:
			msg_hist = []
			for ch in message.guild.text_channels:
				try:
					msg_hist.extend(await ch.history(limit=300).flatten())
				except:
					continue
			msg_hist = [x for x in msg_hist if x.author.id == target_user_id]
		else:
			msg_hist = await c.history(limit=3000).flatten()
		msg_hist_content = [x.clean_content for x in msg_hist if not x.author.bot]
		src_str = "\n".join(msg_hist_content)
		model = markovify.NewlineText(src_str)
		for _ in range(10):
			ret = model.make_short_sentence(500)
			if ret is not None:
				break
		else:
			ret = "<Error: For some reason the chain did not generate an acceptable sentence. Please rerun the command.>"
	await message.channel.send(ret)
	return
コード例 #14
0
ファイル: content.py プロジェクト: NOOBUV/discord-bot
async def send_done_in_channel(user, unique_id):
    ch = client.get_channel(int(os.getenv('STATUS_CHANNEL')))

    url = '/api/v1/contents?filter[unique_id]=' + unique_id
    res = await send_request(method_type="GET", url=url)
    res = res.json()

    # Error in sending data to channel
    # if len(res["data"])==0:

    try:
        question_name = res['data'][0]['attributes']['name']
        question_link = res['data'][0]['attributes']['link']
        infoLogger.info('update-submissions: data successfully parsed')
    except:
        errorLogger.error('Error while parsing data')
        return False

    embed = discord.Embed(
        title='Status Update',
        description='{0} has solved Question `{1}`'.format(
            user.mention, question_name)
    )

    embed.add_field(name="You can too give it a shot now!", value="Try it [here]({0})".format(
        question_link), inline=False)
    # embed.add_field(name="Unique ID", value=(
    #     "Question Unique ID : "+'`'+unique_id+'`'), inline=False)

    confetti_png = str(
        'https://media1.tenor.com/images/ed2bcee37ffb2944ecafec3e852d6014/tenor.gif?itemid=10369910')

    embed.set_thumbnail(url=confetti_png)

    asyncio.ensure_future(ch.send(embed=embed))
    infoLogger.info('Question Status: Embed sent to the channel')
コード例 #15
0
async def command(command: str, message: discord.Message):
    parts = command.split(" ")
    if len(parts) == 1:
        parts.append(str(message.author.id))
    try:
        u = await client.fetch_user(__common__.strip_to_id(parts[1]))
    except TypeError:
        await message.channel.send(
            "Invalid argument: integer ID or mentions are acceptable")
        return
    except:
        isUser = False
    else:
        isUser = True

    s = client.get_guild(__common__.strip_to_id(parts[1]))
    if s is None:
        isServer = False
    else:
        isServer = True

    c = client.get_channel(__common__.strip_to_id(parts[1]))
    if c is None:
        isTextChannel = False
        isVoiceChannel = False
    else:
        if isinstance(c, discord.TextChannel):
            isTextChannel = True
            isVoiceChannel = False
        elif isinstance(c, discord.VoiceChannel):
            isTextChannel = False
            isVoiceChannel = True
        else:
            await message.channel.send(
                "Invalid channel type - handling for this is not implemented. Sorry."
            )
            return

    if isUser and not "--status" in command:
        user_embed = discord.Embed(
            title="User Information",
            description=f"Information about {u.mention}",
            color=0x3127b3)
        user_embed = user_embed.set_thumbnail(url=u.avatar_url)
        user_embed = user_embed.add_field(name="Tag",
                                          value=u.name + "#" + u.discriminator)
        # user_embed = user_embed.add_field(name="Avatar URL", value=u.avatar_url_as(static_format="png", size=1024))
        if message.guild.get_member(u.id) is not None:
            m = message.guild.get_member(u.id)
            user_embed = user_embed.add_field(name="Nickname",
                                              value=m.display_name)
        user_embed = user_embed.add_field(name="Raw ID", value=u.id)
        # user_embed = user_embed.add_field(name="Is Bot", value=u.bot)
        ctime_str = f"{str(u.created_at)}\n({str(datetime.datetime.utcnow()-u.created_at)})"
        user_embed = user_embed.add_field(name="Account Creation Time",
                                          value=ctime_str)
        if get_any_member(u.id) is not None:
            m = get_any_member(u.id)
            user_embed = user_embed.add_field(
                name="Current Status",
                value=f"Apparent Status: {status_emoji(m.status)}\n"
                f"Desktop: {status_emoji(m.desktop_status)}\n"
                f"Web: {status_emoji(m.web_status)}\n"
                f"Mobile: {status_emoji(m.mobile_status)}\n",
                inline=True)
        if message.guild.get_member(u.id) is not None:
            m = message.guild.get_member(u.id)
            jtime_str = f"{str(m.joined_at)}\n({str(datetime.datetime.utcnow()-m.joined_at)})"
            user_embed = user_embed.add_field(name="Joined this server",
                                              value=jtime_str)
            roles = "\n".join([f"{x.name} ({x.id})" for x in m.roles][::-1])
            user_embed = user_embed.add_field(name="Roles in this server",
                                              value=roles,
                                              inline=False)
        user_embed = user_embed.set_footer(text=__common__.get_timestamp())

    if isUser and "--status" in command:
        if get_any_member(u.id) is not None:
            m = get_any_member(u.id)
        else:
            return await message.channel.send(
                "Cannot get status: I do not share any servers with this user (in order to get a user's status I must share a server with them)"
            )
        user_embed = discord.Embed(
            description=f"Apparent Status: {status_emoji(m.status)}\n"
            f"Desktop: {status_emoji(m.desktop_status)}\n"
            f"Web: {status_emoji(m.web_status)}\n"
            f"Mobile: {status_emoji(m.mobile_status)}\n"
            f"Is on mobile? {m.is_on_mobile()}", )
        user_embed = user_embed.set_author(icon_url=m.avatar_url_as(
            format="png", size=128),
                                           name=f"{m.name}#{m.discriminator}")
        user_embed = user_embed.set_footer(text=__common__.get_timestamp())

    if isServer:
        server_embed = discord.Embed(title="Server Information",
                                     color=0xb368a2)
        server_embed = server_embed.add_field(name="Name", value=s.name)
        server_embed = server_embed.add_field(name="Raw ID", value=s.id)
        icon = s.icon_url_as(format="png", size=1024)
        if not icon:  # Used to be != "" before icon was a discord.Asset, credit to eyyyyyy for finding/fixing this
            icon = "[no custom icon]"
            server_embed = server_embed.set_thumbnail(url=s.icon_url)
        server_embed = server_embed.add_field(name="Icon URL", value=icon)
        server_embed = server_embed.add_field(
            name="Owner",
            value=f"{s.owner.name}#{s.owner.discriminator}\nID {s.owner.id}")
        server_embed = server_embed.add_field(name="Member Count",
                                              value=s.member_count)
        server_embed = server_embed.add_field(name="Role Count",
                                              value=len(s.roles))
        server_embed = server_embed.add_field(name="Emoji Count",
                                              value=len(s.emojis))
        server_embed = server_embed.add_field(name="Creation Time",
                                              value=s.created_at)
        server_embed = server_embed.add_field(name="Region", value=s.region)
        server_embed = server_embed.add_field(name="Is offline?",
                                              value=s.unavailable)
        server_embed = server_embed.add_field(name="Admin 2FA required?",
                                              value=bool(s.mfa_level))
        server_embed = server_embed.add_field(name="Verification Level",
                                              value=s.verification_level)
        server_embed = server_embed.set_footer(text=__common__.get_timestamp())

    if isTextChannel:
        channel_embed = discord.Embed(
            title="Channel Information",
            description=f"Information about the text channel {c.mention}",
            color=0x8f44a2)
        channel_embed = channel_embed.add_field(name="Name", value=c.name)
        channel_embed = channel_embed.add_field(name="ID", value=c.id)
        channel_embed = channel_embed.add_field(
            name="Server", value=f"{c.guild.name} ({c.guild.id})")
        t = c.topic
        if t == "":
            t = "[none]"
        channel_embed = channel_embed.add_field(name="Topic",
                                                value=t,
                                                inline=False)
        channel_embed = channel_embed.add_field(name="Creation Time",
                                                value=c.created_at)

    if isVoiceChannel:
        channel_embed = discord.Embed(
            title="Channel Information",
            description=f"Information about the voice channel {c.name}",
            color=0x8f44a2)
        channel_embed = channel_embed.add_field(name="Name", value=c.name)
        channel_embed = channel_embed.add_field(name="ID", value=c.id)
        channel_embed = channel_embed.add_field(
            name="Server", value=f"{c.guild.name} ({c.guild.id})")
        channel_embed = channel_embed.add_field(name="Bitrate",
                                                value=c.bitrate)
        channel_embed = channel_embed.add_field(name="User Limit",
                                                value=c.user_limit)
        channel_embed = channel_embed.add_field(name="Creation Time",
                                                value=c.created_at)
        in_vc = "\n".join([
            f"{x.display_name} ({x.name}#{x.discriminator} - {x.id})"
            for x in c.members
        ])
        if in_vc == "":
            in_vc = "[none]"
        channel_embed = channel_embed.add_field(
            name="Members Currently In Channel", value=in_vc)

    if isUser:
        await message.channel.send(embed=user_embed)
        await asyncio.sleep(0.05)

    if isServer:
        await message.channel.send(embed=server_embed)
        await asyncio.sleep(0.05)

    if isTextChannel or isVoiceChannel:
        channel_embed = channel_embed.set_footer(
            text=__common__.get_timestamp())
        await message.channel.send(embed=channel_embed)
        await asyncio.sleep(0.05)

    if not (isUser or isServer or
            (isTextChannel
             or isVoiceChannel)):  # if not a user, server, or channel:
        await message.channel.send(
            f"Unknown user, server, or channel with ID {parts[1]}. I might not be able to 'see' that object."
        )
    return
コード例 #16
0
ファイル: silence.py プロジェクト: GilbertzRivi/smokel
async def silence(ctx, arg):
    if ctx.author != vrb.host or not vrb.kanclerz in ctx.author.roles:
        await ctx.send('Nie masz uprawnień')
        return

    if arg == 'on':
        letters = ascii_letters
        safety_string = ''.join(choice(letters) for i in range(6))
        await ctx.send(
            f'Wpisz ten ciąg znaków aby potwierdzić decyzję o zablokowaniu wszystkich kanałów serwera\n``{safety_string}``'
        )

        def check(m):
            return m.content == safety_string and m.author == ctx.author and m.channel == ctx.channel

        try:
            await client.wait_for('message', timeout=15.0, check=check)
        except TimeoutError:
            await ctx.channel.send('Czas minął')
            return

        loading = await ctx.send('``Wyciszanie trwa\n' + 25 * '-' + '``')
        loading_counter = 0
        json_add('commands/for_host/silence.json', ['silenced'], True)
        for channel in ctx.guild.text_channels:
            loading_progress = int(loading_counter / len(ctx.guild.channels) *
                                   25)
            for role in channel.changed_roles:
                await channel.set_permissions(role, overwrite=None)
            await channel.set_permissions(ctx.guild.default_role,
                                          read_messages=False)
            await loading.edit(content='``Wyciszanie trwa\n' +
                               loading_progress * '#' +
                               (25 - loading_progress) * '-' + '``')
            loading_counter += 1
        silenced = await ctx.guild.create_text_channel(
            name='inf kryzysowa',
            overwrites={
                ctx.guild.default_role:
                PermissionOverwrite(send_messages=False)
            })
        await silenced.send(
            'Przepraszamy ale wystąpiła sytuacja kryzysowa i serwer będzie niedostępny przez pewien okres czasu.\nAdministracja zajmuje się sytuacją i powinna wam przekazać więcej informacji.'
        )
        await loading.edit(content='``Done\n' + 25 * '#' + '``')

    if arg == 'off':
        all_chans = loads(
            read('commands/for_host/silence.json'))['saved_perms']
        loading = await ctx.send('``Odciszanie trwa\n' + 25 * '-' + '``')
        loading_counter = 0
        for chan_id in all_chans:
            channel = client.get_channel(int(chan_id))
            await channel.set_permissions(ctx.guild.default_role,
                                          overwrite=None)
            for role_id in all_chans[chan_id]:
                perms = all_chans[chan_id][role_id]
                role = ctx.guild.get_role(int(role_id))
                if len(perms) == 0: continue
                await channel.set_permissions(role, **perms)
            loading_progress = int(loading_counter / len(ctx.guild.channels) *
                                   25)
            await loading.edit(content='``Odciszanie trwa\n' +
                               loading_progress * '#' +
                               (25 - loading_progress) * '-' + '``')
            loading_counter += 1
        await loading.edit(content='``Done\n' + 25 * '#' + '``')

        json_add('commands/for_host/silence.json', ['silenced'], False)
コード例 #17
0
async def handle_input(data, writer: asyncio.StreamWriter):
    format = data.get("type", None)
    if format is None:
        # if the client won't tell us what they're sending why should we even bother
        log.warning(
            f"server: Broken client sent data without a type. Dropping")
        raise TypeError("Invalid packet (no type given)")

    if format == "ping":
        # Send back a double with ping time in ms
        writer.write(struct.pack(">d", client.latency * 1000))
        await writer.drain()
        return

    if format == "status":

        # Send back a whole dict of information
        response = {
            "time": time.time(),
            "active": client.active,
            "uptime": time.perf_counter() - client.first_execution,
            "latency": client.latency * 1000,
            "servers": len(client.guilds),
            "msg_count": client.message_count,
            "cmd_count": client.command_count,
            "cache_len": len(client._connection._messages),
            "pid": os.getpid(),
            "hostname": socket.gethostname(),
            "cpu_temp":
            psutil.sensors_temperatures()['cpu-thermal'][0].current,
        }

        response = json.dumps(response).encode()
        length = len(response)
        response = struct.pack(">L", length) + response
        writer.write(response)
        await writer.drain()
        return

    if format == "msg_send":

        target_id = data.get("id", None)
        message = data.get("msg", "")
        if target_id is None:
            raise ValueError("No target provided")
        if message == "":
            raise ValueError("No message provided")

        target: discord.User = client.get_user(target_id)
        if target is None:
            target: discord.TextChannel = client.get_channel(target_id)
            if target is None:
                raise LookupError("Unknown recipient")
            assert isinstance(target, discord.TextChannel)
        else:
            assert isinstance(target, discord.User)

        try:
            msg = await target.send(message)
        except discord.Forbidden as exc:
            response = {
                "success": False,
                "error": "Invalid Permissions",
                "description": f"Forbidden: {str(exc)}"
            }
        except discord.HTTPException as exc:
            response = {
                "success": False,
                "error": "Message Send Failure",
                "description": f"HTTPException: {str(exc)}"
            }
        except Exception as exc:
            response = {
                "success": False,
                "error": "Unknown error",
                "description": str(exc)
            }
        else:
            response = {
                "success": True,
                "time": str(msg.created_at),
                "guild": msg.guild.name,
                "channel": msg.channel.name,
            }
        response = json.dumps(response).encode()
        response = struct.pack(">L", len(response)) + response
        writer.write(response)
        await writer.drain()
        return

    if format == "enable":
        client.active = True
        writer.write(struct.pack(">L?", 1, True))
        await writer.drain()
        return

    if format == "disable":
        client.active = False
        writer.write(struct.pack(">L?", 1, True))
        await writer.drain()
コード例 #18
0
ファイル: foxxo.py プロジェクト: ntoskrnl4/arbys
from client import client
from typing import List, Tuple

import discord
import log
import random

if client.is_ready():
	foxxo_channel = client.get_channel(526155899295891456)
	foxxo_channel_cache = []
	
	wolfie_channel = client.get_channel(565247287534682112)
	wolfie_channel_cache = []
	
	doggo_channel = client.get_channel(564533446504873986)
	doggo_channel_cache = []
	
	raccoon_channel = client.get_channel(563314782141153321)
	raccoon_channel_cache = []
else:
	foxxo_channel = None
	foxxo_channel_cache = None
	
	wolfie_channel = None
	wolfie_channel_cache = None
	
	doggo_channel = None
	doggo_channel_cache = None
	
	raccoon_channel = None
	raccoon_channel_cache = None
コード例 #19
0
async def command(parts: str, message: discord.Message):
    parts = parts.split(" ")

    response = discord.Embed()

    # get all optional arguments and check them
    try:
        charlimit = parts.pop(parts.index("--charlimit") + 1)
        parts.pop(parts.index("--charlimit"))
    except IndexError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: No number provided after --charlimit argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return
    except ValueError:
        charlimit = 1500

    try:
        attempts = parts.pop(parts.index("--attempts") + 1)
        parts.pop(parts.index("--attempts"))
    except IndexError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: No number provided after --attempts argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return
    except ValueError:
        attempts = 25

    try:
        size = parts.pop(parts.index("--size") + 1)
        parts.pop(parts.index("--size"))
    except IndexError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: No number provided after --size argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return
    except ValueError:
        size = 3

    try:
        charlimit = int(charlimit)
    except ValueError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: Invalid number passed as --charlimit argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return

    try:
        attempts = int(attempts)
    except ValueError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: Invalid number passed as --attempts argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return

    try:
        size = int(size)
    except ValueError:
        response.colour = 0xb81209
        response.title = "Markov function error"
        response.description = "Argument error: Invalid number passed as --size argument"
        response.set_footer(text=datetime.utcnow().__str__())
        await message.channel.send(embed=response)
        return

    # determine our target.
    target = None
    target_type = "unknown"
    # check for nothing
    if len(parts) is 1:
        target = message.channel
        target_type = "channel"

    if len(parts) > 1:

        # get channel if it is one
        c = client.get_channel(__common__.stripMentionsToID(parts[1]))
        if c is not None:
            target = c
            target_type = "channel"

        u = client.get_user(__common__.stripMentionsToID(parts[1]))
        if u is not None:
            target = u
            target_type = "user"

    if target_type == "unknown":
        response.colour = 0xb81209
        response.title = f"Markov function failed"
        response.description = "Error running markov function: Unknown object specified"
        response.set_footer(
            text=
            f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name}"
        )
        await message.channel.send(embed=response)

    # run different outputs for different input types
    if target_type == "user":
        async with message.channel.typing():
            target_member = message.guild.get_member(target.id)
            if target_member is not None:
                display_target = f"{target_member.display_name}"
            else:
                display_target = f"{target.name}#{target.discriminator}"

            try:
                count, result = await get_user_markov(target.id, message, size,
                                                      charlimit, attempts)
            except KeyError:
                await message.channel.send(
                    f"{message.author.mention} The user you have specified has had no recent messages. This function only works on users who have been active recently."
                )
                return

            if result is None:
                response.colour = 0xb81209
                response.title = "Markov function failed"
                response.description = "Unable to run markov chain - try running the command again"
                response.set_author(name=display_target,
                                    icon_url=target.avatar_url_as(format="png",
                                                                  size=128))
                response.set_footer(
                    text=
                    f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name} | {count} messages in input"
                )
                await message.channel.send(embed=response)
                return

            response.colour = 0x243b61
            response.description = result
            response.set_author(name=display_target,
                                icon_url=target.avatar_url_as(format="png",
                                                              size=128))
            response.set_footer(
                text=
                f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name} | {count} messages in input"
            )
        await message.channel.send(embed=response)
        return

    if target_type == "channel":
        async with message.channel.typing():
            count, result = await get_channel_markov(target, size, charlimit,
                                                     attempts)

            if count is None:  # permissions error
                response.colour = 0xb81209
                response.title = "Markov chain failed"
                response.description = "Unable to run markov chain: Insufficient permissions to read channel history"
                response.set_footer(
                    text=
                    f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name}"
                )
                response.set_author(name=f"#{target.name}")
                # if we can't read the channel we should check if we can write to it also
                try:
                    await message.channel.send(embed=response)
                except discord.Forbidden:
                    pass

            if result is None:
                response.colour = 0xb81209
                response.title = "Markov function failed"
                response.description = "Unable to run markov chain - try running the command again"
                response.set_footer(
                    text=
                    f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name} | {count} messages in input"
                )
                response.set_author(name=f"#{target.name}")
                await message.channel.send(embed=response)
                return

            response.colour = 0x243b61
            response.description = result
            response.set_footer(
                text=
                f"{datetime.utcnow().__str__()} | Markov run by @{message.author.display_name} | {count} messages in input"
            )
            response.set_author(name=f"#{target.name}")
        await message.channel.send(embed=response)
        return
    return
コード例 #20
0
async def command(command: str, message: discord.Message):
	try:
		try:
			u = await client.get_user_info(__common__.stripMentionsToID(command[6:]))
		except:
			isUser = False
		else:
			isUser = True

		s = client.get_guild(__common__.stripMentionsToID(command[6:]))
		if s is None:
			isServer = False
		else:
			isServer = True

		c = client.get_channel(__common__.stripMentionsToID(command[6:]))
		if c is None:
			isTextChannel = False
			isVoiceChannel = False
		else:
			if isinstance(c, discord.TextChannel):
				isTextChannel = True
				isVoiceChannel = False
			elif isinstance(c, discord.VoiceChannel):
				isTextChannel = False
				isVoiceChannel = True
			else:
				await message.channel.send("Invalid channel type - handling for this is not implemented. Sorry.")
				return

	except ValueError:
		u = message.author
		isUser = True
		s = message.guild
		isServer = True
		c = message.channel
		isTextChannel = True
		isVoiceChannel = False

	if isUser:
		user_embed = discord.Embed(title="User Information", description=f"Information about {u.mention}", color=0x3127b3)
		user_embed = user_embed.set_thumbnail(url=u.avatar_url_as(static_format="png", size=1024))
		user_embed = user_embed.add_field(name="Human-Friendly User ID", value=u.name+"#"+u.discriminator)
		user_embed = user_embed.add_field(name="User Avatar URL", value=u.avatar_url_as(static_format="png", size=1024))
		user_embed = user_embed.add_field(name="Raw User ID", value=u.id)
		user_embed = user_embed.add_field(name="Is Bot", value=u.bot)
		user_embed = user_embed.add_field(name="Account Creation Time", value=u.created_at)
		if message.guild.get_member(u.id) is not None:
			m = message.guild.get_member(u.id)
			roles = "\n".join([f"{x.name} ({x.id})" for x in m.roles][::-1])
			user_embed = user_embed.add_field(name="Roles in this server", value=roles, inline=False)
			user_embed = user_embed.add_field(name="User Nickname", value=m.display_name)
			user_embed = user_embed.add_field(name="Joined this server on", value=m.joined_at.__str__())

	if isServer:
		server_embed = discord.Embed(title="Server Information", description=f"Information about the server {s.name}", color=0xb368a2)
		server_embed = server_embed.set_thumbnail(url=s.icon_url)
		server_embed = server_embed.add_field(name="Name", value=s.name)
		server_embed = server_embed.add_field(name="Raw ID", value=s.id)
		icon = s.icon_url_as(format="png", size=1024)
		if icon == "":
			icon = "[no custom icon]"
		server_embed = server_embed.add_field(name="Icon URL", value=icon)
		server_embed = server_embed.add_field(name="Owner", value=f"{s.owner.name}#{s.owner.discriminator} ({s.owner.id})")
		server_embed = server_embed.add_field(name="Creation Time", value=s.created_at)
		server_embed = server_embed.add_field(name="Member Count", value=s.member_count)
		server_embed = server_embed.add_field(name="Role Count", value=len(s.roles))
		server_embed = server_embed.add_field(name="Emoji Count", value=len(s.emojis))
		server_embed = server_embed.add_field(name="Region", value=s.region)
		server_embed = server_embed.add_field(name="Is offline?", value=s.unavailable)
		server_embed = server_embed.add_field(name="Admin 2FA required?", value=s.mfa_level)
		server_embed = server_embed.add_field(name="Verification Level", value=s.verification_level)

	if isTextChannel:
		channel_embed = discord.Embed(title="Channel Information", description=f"Information about the text channel {c.mention}", color=0x8f44a2)
		channel_embed = channel_embed.add_field(name="Name", value=c.name)
		channel_embed = channel_embed.add_field(name="ID", value=c.id)
		channel_embed = channel_embed.add_field(name="Server", value=f"{c.guild.name} ({c.guild.id})")
		t = c.topic
		if t == "":
			t = "[none]"
		channel_embed = channel_embed.add_field(name="Topic", value=t, inline=False)
		channel_embed = channel_embed.add_field(name="Creation Time", value=c.created_at)

	if isVoiceChannel:
		channel_embed = discord.Embed(title="Channel Information", description=f"Information about the voice channel {c.name}", color=0x8f44a2)
		channel_embed = channel_embed.add_field(name="Name", value=c.name)
		channel_embed = channel_embed.add_field(name="ID", value=c.id)
		channel_embed = channel_embed.add_field(name="Server", value=f"{c.guild.name} ({c.guild.id})")
		channel_embed = channel_embed.add_field(name="Bitrate", value=c.bitrate)
		channel_embed = channel_embed.add_field(name="User Limit", value=c.user_limit)
		channel_embed = channel_embed.add_field(name="Creation Time", value=c.created_at)
		in_vc = "\n".join([f"{x.display_name} ({x.name}#{x.discriminator} - {x.id})" for x in c.members])
		if in_vc == "":
			in_vc = "[none]"
		channel_embed = channel_embed.add_field(name="Members Currently In Channel", value=in_vc)

	if isUser:
		await message.channel.send(embed=user_embed)
		await asyncio.sleep(0.05)

	if isServer:
		await message.channel.send(embed=server_embed)
		await asyncio.sleep(0.05)

	if isTextChannel or isVoiceChannel:
		await message.channel.send(embed=channel_embed)
		await asyncio.sleep(0.05)

	if not (isUser or isServer or (isTextChannel or isVoiceChannel)):  # if not a user, server, or channel:
		await message.channel.send(f"Unknown user, server, or channel with ID {command[6:]}. I might not be able to 'see' that object.")
	return