Exemple #1
0
def load_cogs(client: commands.AutoShardedBot):
    for cog_name in os.listdir('./Cogs'):
        if cog_name.endswith('.py'):
            try:
                client.load_extension(f"Cogs.{cog_name.replace('.py', '')}")
                Logger.Console.Cogs.cog_loaded(cog_name)
            except Exception as error:
                Logger.Console.Cogs.cog_errored(cog_name, error)
Exemple #2
0
    def __init__(self):
        self.bot = AutoShardedBot(command_prefix=Guild.get_prefix)
        self.bot.remove_command('help')

        for cog in [
                Arranger, Cataloguer, Encoder, Gambler, Hearer, Helper, Logger,
                Quoter, Recaller
        ]:
            self.bot.add_cog(cog(self.bot))
Exemple #3
0
async def init_timed_events(client: AutoShardedBot) -> None:
    """Create a listener task with a tick-rate of 1s"""

    await client.wait_until_ready()  # Wait for the bot to launch first
    client.secs = 0

    secs = 0  # Keep track of the number of secs so we can access it elsewhere and adjust how often things run
    while True:
        client.dispatch("timer_update", secs)
        await timer_update(secs)
        secs += 1
        client.secs = secs
        await asyncio.sleep(1)
Exemple #4
0
    def __init__(self, bot: AutoShardedBot):
        self.bot = bot

        if not hasattr(
                bot, 'lavalink'
        ):  # This ensures the client isn't overwritten during cog reloads.
            bot.lavalink = lavalink.Client(BOTID)
            bot.lavalink.add_node(
                '127.0.0.1', 2333, 'youshallnotpass', 'eu',
                'default-node')  # Host, Port, Password, Region, Name
            bot.add_listener(bot.lavalink.voice_update_handler,
                             'on_socket_response')

        lavalink.add_event_hook(self.track_hook)
Exemple #5
0
def mention_to_member(bot: commands.AutoShardedBot, guild_id: int,
                      user_mention: str) -> discord.User:
    """
    Turns a discord user mention into a discord.py member object.
    """
    user_id = int(user_mention[3:].split(">")[0])
    return bot.get_guild(guild_id).get_member(user_id)
Exemple #6
0
async def embed_faq(ctx: commands.Context,
                    bot: commands.AutoShardedBot,
                    query: str,
                    title: str = None,
                    color: str = None) -> discord.Embed:
    """
    Returns a discord.Embed derived from the parameters given
    """
    queryRow = await faqdb(ctx, query)
    if queryRow[6] is not None:  # link
        queryRow = await faqdb(ctx, str(queryRow[6]))
    if not title:
        title = str(queryRow[1]).title()
    if not color:
        color = discord.Colour.gold()
    image = None if queryRow[3] is None else str(queryRow[3])
    author_id = int(queryRow[4])
    author = bot.get_user(author_id) or await bot.fetch_user(author_id)
    authorName = getattr(await lazily_fetch_member(ctx.guild, author.id),
                         "display_name", None)
    if authorName is not None and author.avatar:
        authorPic = f"https://cdn.discordapp.com/avatars/{author.id}/{author.avatar}.png?size=64"
    else:
        authorPic = "https://cdn.discordapp.com/embed/avatars/0.png"
    em = discord.Embed(
        title=title,
        description="" if queryRow[2] is None else str(queryRow[2]),
        timestamp=datetime.datetime.strptime(queryRow[5],
                                             "%Y-%m-%d %H:%M:%S.%f%z"),
        colour=color)
    if image:
        em.set_image(url=image)
    em.set_author(name=authorName or "Unknown", icon_url=authorPic)
    return em
Exemple #7
0
    def __init__(self, bot: commands.AutoShardedBot):
        self.bot = bot
        self.name = "MusicV3"
        if not hasattr(bot, 'wavelink'):
            bot.wavelink = wavelink.Client(bot=bot)

        bot.loop.create_task(self.start_nodes())
Exemple #8
0
 def __init__(self, bot: AutoShardedBot, *args, **kwargs):
     self.bot = bot
     global orig_help
     orig_help = bot.get_command('help')
     self.bot.remove_command('help')
     self.bot.formatter = self
     self.bot.help_formatter = self
     super().__init__(*args, **kwargs)
Exemple #9
0
async def setup_database(
        bot: commands.AutoShardedBot,
        keys: ClassyDict) -> None:  # init pool connection to database
    bot.db = await asyncpg.create_pool(
        host=keys.database.host,  # where db is hosted
        database=keys.database.name,  # name of database
        user=keys.database.user,  # database username
        password=keys.database.passw,  # password which goes with user
        max_size=20,
        command_timeout=10,
    )
Exemple #10
0
import os

from aiohttp import AsyncResolver, ClientSession, TCPConnector

from discord import Game
from discord.ext.commands import AutoShardedBot, when_mentioned_or

from bot.formatter import Formatter
from bot.utils import CaseInsensitiveDict

bot = AutoShardedBot(
    command_prefix=when_mentioned_or(
        ">>> self.", ">> self.", "> self.", "self.",
        ">>> bot.", ">> bot.", "> bot.", "bot.",
        ">>> ", ">> ", "> ",
        ">>>", ">>", ">"
    ),  # Order matters (and so do commas)
    activity=Game(name="with snekky sneks"),
    help_attrs={"aliases": ["help()"]},
    formatter=Formatter()
)

# Make cog names case-insensitive
bot.cogs = CaseInsensitiveDict()

# Global aiohttp session for all cogs - uses asyncio for DNS resolution instead of threads, so we don't *spam threads*
bot.http_session = ClientSession(connector=TCPConnector(resolver=AsyncResolver()))

# Internal/debug
bot.load_extension("bot.cogs.logging")
bot.load_extension("bot.cogs.security")
Exemple #11
0
 def __init__(self, bot: AutoShardedBot):
     self.bot = bot
     self._original_help_command = bot.help_command
     bot.help_command = MyHelpCommand()
     bot.help_command.cog = self
Exemple #12
0
def setup(bot: Bot):
    bot.add_cog(ReactionRole(bot))
Exemple #13
0
from discord.ext import commands
from discord.ext.commands import AutoShardedBot
from discord_slash import SlashCommand
import asyncio
from cogs.api.mongo import Document
import motor.motor_asyncio

# bot token you can get from: https://discord.com/developers/applications/
TOKEN = ""
# create a free mongodb data base here: https://www.mongodb.com/3 and connect it
MONGODBCONNECTION = ""

intents = discord.Intents.default()
intents.members = True
#bot = commands.Bot(command_prefix='!')
bot = AutoShardedBot(command_prefix="!", intents=intents)
slash = SlashCommand(
    bot, sync_commands=True,
    sync_on_cog_reload=True)  # Declares slash commands through the client.

# # uncomment after you setup the file within cogs/cogname to use it:

# # our report system: https://discord.com/channels/513749917567811586/794188772237377586/794199015025278979
# bot.load_extension("cogs.bob_reports")

# # creates a welcome message if someone joins and gives the bros army role
# bot.load_extension("cogs.bob_only")

# # makes temporary voice channels that automaticly get removed when its empty
# bot.load_extension("cogs.voice")
Exemple #14
0
import discord
from discord.ext.commands import AutoShardedBot, when_mentioned_or
import pymongo

modulos = ["cogs.comando"]

# Evento do client
client = AutoShardedBot(command_prefix="!", case_insensitive=True)


# evento do on_ready
@client.event
async def on_ready():
    print(f"{client.user.name} Online hihi.")
    await client.change_presence(activity=discord.Streaming(
        name="!help", url="https://www.twitch.tv/123"))


client.db = pymongo.MongoClient("Informe sua Database")["discord"]

if __name__ == "__main__":
    for modulo in modulos:
        # Função para carregar um modulo
        try:
            client.load_extension(modulo)
        except Exception as e:
            print("Erro ao carregar cog {modulo}\nErro:{e}")

# Irá coletar o token do bot
    client.run("Informe seu token")
Exemple #15
0
# coding=utf-8
import os

from aiohttp import AsyncResolver, ClientSession, TCPConnector
from discord import Game
from discord.ext.commands import AutoShardedBot, when_mentioned_or

from bot.formatter import Formatter

bot = AutoShardedBot(
    command_prefix=when_mentioned_or(
        "self.", "bot."
    ),
    activity=Game(
        name="Help: bot.help()"
    ),
    help_attrs={
        "name": "help()",
        "aliases": ["help"]
    },
    formatter=Formatter(),
    case_insensitive=True
)

# Global aiohttp session for all cogs - uses asyncio for DNS resolution instead of threads, so we don't *spam threads*
bot.http_session = ClientSession(connector=TCPConnector(resolver=AsyncResolver()))

# Internal/debug
bot.load_extension("bot.cogs.logging")
bot.load_extension("bot.cogs.security")
bot.load_extension("bot.cogs.events")
Exemple #16
0
                                     ).run(bot.connection))

        valid.extend([custom])
    else:
        valid.extend(bot.config.get('prefixes'))

    return valid


if __name__ == '__main__':
    r.set_loop_type('asyncio')

    with open('config.json') as f:
        config = json.load(f)

    bot = AutoShardedBot(command_prefix=get_prefix,
                         help_attrs=dict(hidden=True))
    bot.startup = datetime.now()
    bot.messages_seen = 0
    bot.r = r
    bot.connection = bot.loop.run_until_complete(r.connect(db='parallax'))
    bot.db = database.Database(bot)
    bot.config = config

    for f in os.listdir('extensions'):
        if f.endswith('.py'):
            try:
                bot.load_extension(f'extensions.{f[:-3]}')
            except SyntaxError as exception:
                print(f'Failed to load {f}: {exception}')

    @bot.event
Exemple #17
0
def teardown(bot: commands.AutoShardedBot, ):
    """Remove the cog from the bot."""
    bot.remove_cog("User")
REWARD = 200
ENABLE_REWARD = True

DBHOST = config.mysql.host
DBUSER = config.mysql.user
DBNAME = config.mysql.dbname
DBPASS = config.mysql.password

# word file names
WORDLIST_1 = config.listfile.file1
WORDLIST_2 = config.listfile.file2
WORDLIST_3 = config.listfile.file3

BADWORD_1 = config.listfile.badword1

bot = AutoShardedBot(command_prefix=['.', '!', '?'], case_insensitive=True)
bot.remove_command("help")

IN_PUZZLEWORD = False
conn = None


def openConnection():
    global conn
    try:
        if conn is None:
            conn = pymysql.connect(DBHOST,
                                   user=DBUSER,
                                   passwd=DBPASS,
                                   db=DBNAME,
                                   charset='utf8mb4',
Exemple #19
0
import discord
from discord.ext.commands import AutoShardedBot, when_mentioned_or
import dados

client = AutoShardedBot(command_prefix=when_mentioned_or(dados.prefix()), case_insensitive=True)

@client.event
async def on_ready():
    print(f"Nenhum virus encontrado - Bot name {client.user.name} Id do bot encontrado ({client.user.id})")
    await client.change_presence(activity=discord.Streaming(name="digite s.ajuda", url="https://www.twitch.tv/nkoficial"))


def run_modules():

	try:
	  client.remove_command("help")
	  print("Um virus foi abatido -- comando help removido.")
	  for modulos in dados.modulos():
	  	 client.load_extension(modulos)
	  print(f"[Ok] nenhum virus detectado - {len(dados.modulos())} modulos carregados.")
	except Exception as e:
		print(f"Um virus foi detectado: O {modulos} Não foi carregado pelo motivo = {e}")

	try:
	  client.run(dados.token())
	  print(f"Nenhum virus foi detectado -- Bot foi carregado")
	except Exception as e:
		print(f"Um virus foi detectado: O bot não conseguiu se conectar ao discord  = {e}")

if __name__ == '__main__':
	run_modules()
Exemple #20
0
def teardown(bot: commands.AutoShardedBot, ):
    """Remove the cog from the bot."""
    bot.remove_cog(config["tbgs"]["name"])
Exemple #21
0
def setup(client: commands.AutoShardedBot):
    client.add_cog(BenBot(client))
Exemple #22
0
 def setup(cls, bot: commands.AutoShardedBot):
     """
     Sets up the current cog.
     """
     instance = cls(bot)
     bot.add_cog(instance)
Exemple #23
0
from dotenv import load_dotenv
from slashify import Slashify
from termcolor import cprint

from cogs.utils import Config, Logger, Strings, Utils

CONFIG = Config()
STRINGS = Strings(CONFIG["default_locale"])

filepath = dirname(abspath(__file__))

cprint(STRINGS["etc"]["info"]["art"], "white")

cprint("Default locale is {0}".format(CONFIG["default_locale"]), "green")

bot = AutoShardedBot(command_prefix=Utils.get_prefix, help_command=None)


@bot.event
async def on_ready() -> NoReturn:
    for filename in os.listdir(filepath + "/cogs/"):
        if filename.endswith(".py"):
            bot.load_extension("cogs.{0}".format(filename[:-3]))

    await bot.change_presence(activity=discord.Game(name="..."))
    bot.load_extension("jishaku")
    Logger.done(STRINGS["bot_log"]["logged_as"].format(bot.user))


bot.run(CONFIG["token"])
Exemple #24
0
from discord.ext.commands import AutoShardedBot as Bot
import os


bot = Bot(command_prefix="e;r ")
bot.load_extension("cogs.reaction_role")

bot.run(os.environ["DISCORD_ACCESS_TOKEN"])
Exemple #25
0
Informações sobre a Biblioteca gTTS
https://pypi.org/project/gTTS/
"""


def read_token():
    with open("token.txt", "r") as f:
        lines = f.readlines()
        return lines[0].strip()


token = read_token()

modulos = ["cogs.comandos"]

bot = AutoShardedBot(command_prefix="tts", case_insensitive=True)
# bot.remove_command('help')


@bot.listen("on_command_error")
async def error_handler(ctx, error):
    error = getattr(error, 'original', error)
    if isinstance(error, commands.CommandOnCooldown):
        s = error.retry_after
        s = round(s, 2)
        h, r = divmod(int(s), 3600)
        m, s = divmod(r, 60)
        return await ctx.send(
            f'Cooldown você precisa esperar **{str(h) + "h : " if h != 0 else ""}{str(m) + "m : " if m != 0 else ""}{str(s) + "s" if s != 0 else ""}** para usar esse comando novamente.'
        )
def setup(client: commands.AutoShardedBot):
    client.add_cog(FortniteAPIio(client))
                              encoding='utf-8',
                              mode='w')
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)


def get_prefix(client, message):
    with open('config.json', 'r') as f:
        prefixes = json.load(f)

    return prefixes['prefix']


bot = AutoShardedBot(command_prefix=get_prefix,
                     pm_help=True,
                     fetch_offline_members=False)
bot.remove_command('help')


@bot.event
async def on_ready():
    print("Bot has been started")
    await bot.change_presence(activity=discord.Activity(
        type=discord.ActivityType.listening, name="rr!help | Reach Radio"))
    with open('config.json', 'r') as f:
        logger = json.load(f)
        log = logger['logger']
        for user in log:
            user = await bot.fetch_user(user)
            await user.send("Reach Radio Public Bot is now ready!")
Exemple #28
0
def setup(client: commands.AutoShardedBot):
    client.add_cog(NiteStats(client))
Exemple #29
0
def setup(bot: AutoShardedBot):
    bot.add_cog(Music(bot))
Exemple #30
0
def setup(bot: commands.AutoShardedBot, ):
    """Add the cog to the bot."""
    bot.add_cog(Usr(bot))