Example #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}")
Example #2
0
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
Example #3
0
async def return_bot_info(command: str, message: discord.Message):
    owner = client.get_user(288438228959363073)
    
    python_version = f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
    if sys.version_info[3] == "alpha":
        python_version += f"a{sys.version_info.serial}"
    if sys.version_info[3] == "beta":
        python_version += f"b{sys.version_info.serial}"
    if sys.version_info[3] == "candidate":
        python_version += f"rc{sys.version_info.serial}"
    
    embed = discord.Embed(title=f"{client.bot_name} info", description=discord.Embed.Empty, color=0x404040)
    embed = embed.add_field(name="Version", value=f"Framework version {client.__version__}")
    embed = embed.add_field(name="Creator", value=f"{owner.name}#{owner.discriminator}\nID {owner.id}\n{owner.mention}")
    embed = embed.add_field(name="Github", value="`ntoskrnl4/arbys`\nhttps://www.github.com/ntoskrnl4/arbys", inline=False)
    embed = embed.add_field(name="Built with", value=f"Running on {python_version}\ndiscord.py library version {discord.__version__}\nntoskrnl-bot framework (`ntoskrnl4/ntoskrnl-bot`)")
    embed = embed.add_field(name="Invite Link", value=discord.utils.oauth_url(client.user.id), inline=False)
    embed = embed.add_field(name="Usage Notice", value="This bot may log messages to disk as part of moderation duties, development debugging, and command usage. Logs will never be used maliciously, are not stored in the cloud, and will not be given to any third party. For comments, questions, concerns, deletion orders, or retrieval requests, please contact ntoskrnl.")
    embed = embed.set_footer(text=__common__.get_timestamp())
    await message.channel.send(embed=embed)
    return
Example #4
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()
Example #5
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
Example #6
0
async def on_message(message):

    await client.process_commands(message)

    if message.author != client.user and not message.mention_everyone:

        if message.author.id == vrb.geralt_id:
            if 'pizda' in message.content.lower() or 'pizdo' in message.content.lower() or 'pizdą' in message.content.lower() or 'pizdy' in message.content.lower():
                await message.channel.send('Pizda <:harold:625405098255843331>', file=discord_file(f'resources/gerwazy_pizda{randint(1,3)}.png', 'gerwazy.png', True))

        if message.content.lower().startswith("rawr"):
            await message.channel.send(choice(["RAWRR!", 'ror']))

        if message.content.lower().startswith("awoo"):
            await message.channel.send(f'*Awo{randint(3, 19)*"o"}!*')
        
        if message.content.split(' ')[0].lower() == "f":
            num = loads(read('config.json'))['counters']['f'] + 1
            if vrb.fem in message.author.roles:
                ending = "oddała"
            else:
                ending = "oddał"
            dedycation = message.content.split(' ')[1:]
            if len(dedycation) > 0:
                if 'dla' in [i.lower() for i in dedycation]:
                    dedycation = ' '.join(dedycation)
                else:
                    dedycation = 'dla ' + ' '.join(dedycation)
            if randint(1, 40) == 10:
                F = discord_file('resources/f.jpg', 'f.jpg', False)
                if len(dedycation) == 0:
                    await  message.channel.send(f"{message.author.display_name} {ending} honory\nHonory oddane w sumie: {num}", file=F)
                else:
                    await  message.channel.send(f'{message.author.display_name} {ending} honory {dedycation}\nHonory oddane w sumie: {num}', file=F)
            else:
                if len(dedycation) == 0:
                    await  message.channel.send(f"{message.author.display_name} {ending} honory\nHonory oddane w sumie: {num}")
                else:
                    await  message.channel.send(f'{message.author.display_name} {ending} honory {dedycation}\nHonory oddane w sumie: {num}')
            json_add('config.json', ['counters', 'f'], num)
        
        if "owo whats this" in message.content or "owo what's this" in message.content:
            owo_whats_this = discord_file('resources/owo.gif', 'owo.gif', False)
            await message.channel.send(file=owo_whats_this)
        
        if message.content.lower() == "whym":
            await message.channel.send("Whymming in progress")
            async for msg in message.channel.history(limit=5):
                if msg.content == "Whymming in progress":
                    break
            for i in range(9):
                await msg.edit(content=f'Whymming in progress{(i%3+1)*"."}')
                sleep(1)
            await msg.edit(content='Whymming complete!', delete_after=5)
        
        bad_words = loads(read('config.json'))['bad_words']
        bad_words_num = loads(read('config.json'))['counters']['bad_words']
        if chk_list_cohesion(bad_words, [i.lower() for i in message.content.split(' ')]):
            counter = 0
            for word in message.content.split(' '):
                if word.lower() in bad_words:
                    counter += 1
            bad_words_num += counter
            json_add('config.json', ['counters', 'bad_words'], bad_words_num)

        if message.content == '.u w u': 
            await message.delete()
            await message.channel.send('u w  u')
            async for msg in message.channel.history(limit=5):
                if msg.content == "u w  u":
                    break
            for i in range(10):
                if i%2 == 0:
                    await msg.edit(content='u  w u')
                else: 
                    await msg.edit(content='u w  u')
                sleep(0.5)
            await msg.delete()

        if message.content.count('kobiet') > 0:
            num = randint(1,100)
            if num == 50:
                await message.channel.send('jezu fuj, weź, kobiety <:tfu:614167432172535831>')

    if len(message.mentions) > 7:
        mentions_no_duplicates = []
        for i in message.mentions:
            if not i in mentions_no_duplicates:
                mentions_no_duplicates.append(i)
        if len(mentions_no_duplicates) > 10:
            message_member = message.guild.get_member(message.author.id)
            try: message_member.remove_roles(vrb.futrzak)
            except: pass
            try: message_member.remove_roles(vrb.nowy)
            except: pass
            await message_member.add_roles(vrb.izolatka)
            for i in vrb.nsfw_chans:
                try: await message_member.remove_roles(i)
                except: pass
            await vrb.tech_chan.send(f'{message.author.mention} oznaczyl wiecej niz 10 osob i dostal izloatke')

    if len(message.mentions) > 0 and client.get_user(614628305047388161) != message.author and message.content[0] != '-' and message.author != client.user:
        for member in message.mentions:
            if str(member.status) == 'idle':
                async for msg in message.channel.history(limit=25):
                    if msg.author.id == member.id:
                        return
                json_file = loads(read('commands/zw.json'))
                if str(member.id) in json_file['dnd']:
                    info = json_file['dnd'][str(member.id)]
                    e = Embed(color=member.color, timestamp=message.created_at)
                    e.set_author(name=f"Użytkownik afk")
                    e.set_thumbnail(url=member.avatar_url)
                    e.add_field(name=f"{member.display_name} jest afk, zostawił wiadomość", value=info)
                    e.set_footer(text='Wiadomość została zostawiona', icon_url=member.avatar_url)
                    await message.channel.send(embed=e)

    if message.content.lower() in responses and message.author != client.user:
        await message.channel.send(responses[message.content.lower()])