예제 #1
0
    async def test_botAssignment(self):
        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler(None)

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler(1)

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler("1")

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler({1: 2})

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler([1, None])

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler(True)

        with self.assertRaises(ValueError):
            # noinspection PyTypeChecker
            AntiSpamHandler(False)

        AntiSpamHandler(commands.Bot(command_prefix="!"))
        AntiSpamHandler(commands.AutoShardedBot(command_prefix="!"))
        AntiSpamHandler(discord.Client())
        AntiSpamHandler(discord.AutoShardedClient())
예제 #2
0
    def __init__(self, instance, shard_count, ids, pipe):
        self.pipe = pipe

        self.bot = commands.AutoShardedBot(command_prefix=_prefix_callable,
                                           shard_count=shard_count,
                                           shard_ids=ids,
                                           help_attrs=dict(Hidden=True),
                                           pm_help=None,
                                           fetch_offline_members=False)
        self.bot.prefix = "n!"
        self.bot.instance = instance
        self.bot.config = json.load(open("config.json"))
        self.bot.command_usage = Counter()
        self.bot.session = aiohttp.ClientSession(loop=self.bot.loop)
        self.bot.counter = Counter()
        self.bot.webhook = self.bot.config["webhook"]

        if not hasattr(self, "uptime"):
            self.bot.uptime = datetime.utcnow()

        self.bot.add_listener(self.on_ready)
        self.bot.add_listener(self.on_message)
        self.bot.run(self.bot.config["token"])

        async def _init_sql():
            self.sql_conn = await aiomysql.create_pool(
                host='localhost',
                port=3306,
                user='******',
                password=self.bot.config["dbpass"],
                db='hentaiboi',
                loop=self.bot.loop,
                autocommit=True)

        self.bot.loop.create_task(_init_sql())
예제 #3
0
def generate_client(loop=None):
    client: commands.Bot = commands.AutoShardedBot(
        command_prefix=get_server_prefix, loop=loop)

    client.remove_command('help')

    for module in MODULES:
        client.load_extension(module)

    client.event(on_command_error)
    client.event(on_error)

    return client
예제 #4
0
def set_bot():
    try:
        import option
    except ModuleNotFoundError:
        print("CatBOT Option File is Missing!")
        print(
            " - Download: https://github.com/chick0/CatBOT/blob/master/option.py"
        )
        sys.exit(-2)

    if option.use_Auto_shard is True:
        return commands.AutoShardedBot(command_prefix=option.prefix)
    else:
        return commands.Bot(command_prefix=option.prefix)
예제 #5
0
    def run(self):
        """
        Run the bot

        --

        :return: `None`
        """

        # Init
        activity = discord.Game(
            name=f"d!help | v{self.__version} - {self.__phase[2]}")

        client = commands.AutoShardedBot(command_prefix=self.__prefix,
                                         help_command=None,
                                         activity=activity)

        logging.basicConfig(level=logging.INFO)

        # Create the database attribute for client
        client.database = Database()

        # Create the logger attribute for the client
        client.logger = CommandLogger(client)

        # Create the needed tables
        client.loop.run_until_complete(client.database.create_game_tables())

        # Set the patreon attribute for client
        # client.patreon = Patreon(client.database)
        # client.loop.run_until_complete(client.patreon.init(os.environ["dbz_patreon_access_token"]))
        # client.loop.run_until_complete(client.patreon.set_premium())

        # Filling up the cache
        client.loop.run_until_complete(CharacterGetter().set_cache(client))
        client.loop.run_until_complete(BannerGetter().set_cache(client))
        client.loop.run_until_complete(MissionGetter().set_cache(client))

        # Loading the commands
        client.loop.run_until_complete(CommandLoader(client).load_commands())

        # Run the bot
        client.run(self.__TOKEN)

        return
예제 #6
0
파일: __main__.py 프로젝트: t41y0u/amiya
def main():
    token = os.getenv("DISCORD_TOKEN")
    if not token:
        logging.error("Discord Token required")
        return

    # Config logging
    logging.basicConfig(
        format="[{asctime}][{levelname}][{name}] {message}",
        style="{",
        datefmt="%d-%m-%Y %H:%M:%S",
        level=logging.INFO,
    )

    # Auto shard
    bot = commands.AutoShardedBot(
        command_prefix=commands.when_mentioned_or(os.getenv("PREFIX")))

    cogs = [file.stem for file in Path("amiya", "cogs").glob("*.py")]
    # Load extensions
    for extension in cogs:
        bot.load_extension(f"amiya.cogs.{extension}")
    logging.info(f'Cogs loaded: {", ".join(bot.cogs)}')

    # Load constants
    constants.setup()
    logging.info(
        f'Constants loaded: {", ".join(filter(lambda x: x.isupper(), dir(constants)))}'
    )

    def no_dm_check(ctx):
        """ Check for DMs """
        if ctx.guild is None:
            raise commands.NoPrivateMessage("Private messages not permitted.")
        return True

    # Restrict bot usage to inside guild channels only.
    bot.add_check(no_dm_check)

    @bot.event
    async def on_ready():
        asyncio.create_task(discord_common.presence(bot))
        logging.info("Successfully logged in and booted...!")

    bot.run(token)
예제 #7
0
파일: bot.py 프로젝트: sh3hz/kdb
from os import environ

from typing import List

from discord.ext import commands

bot = commands.AutoShardedBot(command_prefix='?',
                              pm_help=None,
                              description='bot',
                              shard_count=4)

initial_extensions: List[str] = [
    "cogs.admin", "cogs.fox", "cogs.chatter", "cogs.ascii"
]


def initlialize():
    for extension in initial_extensions:
        bot.load_extension(extension)


initlialize()


@bot.command()
async def halo(ctx):
    await ctx.send(f"Kelkkan {round(bot.latency, 3)}sec  samayam eduthu")


@bot.command()
async def say(ctx, *, args):
예제 #8
0
파일: main.py 프로젝트: WitherredAway/Yeet.
    if not message.guild:
        return prefix
    return commands.when_mentioned_or(*prefixes)(bot, message)


menu = DefaultMenu("◀️", "▶️", "❌", active_time=60)

embed_colour = 0xf1c40f

cmd_cd = 2

log_channel = 837542790119686145

bot = commands.AutoShardedBot(shard_count=2,
                              command_prefix=get_prefix,
                              owner_id=267550284979503104,
                              case_insensitive=True,
                              help_command=PrettyHelp(),
                              self_bot=False)

bot.help_command = PrettyHelp(menu=menu,
                              color=embed_colour,
                              sort_command=False,
                              show_index=True)

for filename in os.listdir('./cogs'):
    if filename.endswith(".py"):
        bot.load_extension(f'cogs.{filename[:-3]}')

keep_alive()
my_secret = os.environ['botTOKEN']
bot.run(my_secret, bot=True)
예제 #9
0
            x.encode().decode()
            for x in Prefix._prefixes["userprefix"][str(message.author.id)]
        ] + ['<@440996323156819968> ']
    except:
        pass
    try:
        return [
            x.encode().decode()
            for x in Prefix._prefixes["serverprefix"][str(message.guild.id)]
        ] + ['<@440996323156819968> ']
    except:
        pass
    return ['sx4 ', 's?', 'S?', '<@440996323156819968> ']


bot = commands.AutoShardedBot(command_prefix=prefix_function)
wrap = "```py\n{}\n```"
dbltoken = Token.dbl()
dbotspwtoken = Token.dbpw()
botspacetoken = Token.botlistspace()
konomitoken = Token.konomi()
dbpwurl = "https://bots.discord.pw/api/bots/440996323156819968/stats"
url = "https://discordbots.org/api/bots/440996323156819968/stats"
botspaceurl = "https://botlist.space/api/bots/440996323156819968/"
konomiurl = "http://bots.disgd.pw/api/bot/440996323156819968/stats"
headers = {"Authorization": dbltoken}
headersdb = {"Authorization": dbotspwtoken, "Content-Type": "application/json"}
headerskon = {"Authorization": konomitoken, "Content-Type": "application/json"}
headersbs = {
    "Authorization": botspacetoken,
    "Content-Type": "application/json"
예제 #10
0
import keep_alive
import logging
import configparser


# Load config.ini
currentPath = os.path.dirname(os.path.realpath(__file__))
configs = configparser.ConfigParser()
configs.read(currentPath + "/config.ini")

# adminUsers gets to load/unload/reload cogs
adminUsers = configs["General"]["adminUsers"].replace("'", "").split(", ")
commandPrefix = configs["General"]["commandPrefix"].replace("'", "").split(", ")

client = commands.AutoShardedBot(
    command_prefix=commands.when_mentioned_or(*commandPrefix), case_insensitive=True
)

# Set up logging to discord.log
logger = logging.getLogger("discord")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
handler.setFormatter(
    logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")
)
logger.addHandler(handler)

keep_alive.keep_alive()


@client.event
예제 #11
0
with open("./Config.yml", 'r') as file:
    config = yaml.load(file)

# Read in permissions settings.
with open("./Permissions.yml", 'r') as file:
    permissions = yaml.load(file)

# The function which allows the command prefix to be changed dynamically.
def get_prefix(client, message):
    with open("./Config.yml", 'r') as file:
        config = yaml.load(file)
    prefix = config['Prefix']
    return prefix

# Create the actual bot instance.
bot = commands.AutoShardedBot(command_prefix = get_prefix, description = "NAU's Welcome Bot", case_insensitive = True)

# I made a custom help command so I remove the default one here.
# Find the custom on in ~/Cogs/Help.py
bot.remove_command('help')

# Setting the main config settings from variables
bot.TOKEN = config['TOKEN']
bot.prefix = config['Prefix']
bot.logs_channels = config['Log Channels']
bot.embed_colors = config['Embed Colors']
bot.footer_icon = config['Footer Icon URL']
bot.footer_text = config['Footer Text']
bot.online_message = config['Online Message']
bot.restarting_message = config['Restarting Message']
bot.data_file = os.path.abspath(config['Data File'])
예제 #12
0
prefix = "cm-"
prefix_list = (prefix, "<@!717062311755513976> ")


async def get_pre(_, message):
    guild_id = message.guild.id
    if PrefixHandler.has_custom_prefix(guild_id):
        guild_prefix = PrefixHandler.get_prefix(guild_id)
        if guild_prefix is not None:
            return (*prefix_list, guild_prefix)
    else:
        return prefix_list


bot = commands.AutoShardedBot(command_prefix=get_pre, shard_count=2)
game = discord.Game(name=f'cm-help')


@bot.event
async def on_ready():
    print('ready')

    await bot.change_presence(status=discord.Status.do_not_disturb,
                              activity=game)


def launchBot(bot: commands.bot):
    bot.load_extension("cogs.utility")
    bot.load_extension("cogs.help")
    bot.load_extension("cogs.owner")
예제 #13
0
import rng
from gtts import gTTS
from discord_slash import SlashCommand, SlashContext
#import rolling
import dad.interface
import cogExample.cogTest
import gameList.interface
import cogDice.cogDice
import heck.interface
import magic8.interface
import smartBot.interface
import slashbot

import voice.interface
client = commands.AutoShardedBot(
    command_prefix=commands.when_mentioned_or('?'),
    description='GU\'s experimental discord ')
slash = SlashCommand(client, override_type=True, sync_commands=True)

client.add_cog(smartBot.interface.smartBot(client))
client.add_cog(dad.interface.Dad(client))
client.add_cog(cogExample.cogTest.Greetings(client))
client.add_cog(gameList.interface.GameList(client))
client.add_cog(cogDice.cogDice.Dice(client))
client.add_cog(heck.interface.Heck(client))
client.add_cog(magic8.interface.Magic8(client))
client.add_cog(voice.interface.Voice(client))
client.add_cog(slashbot.Slash(client))


@client.event
예제 #14
0
def get_prefix(bot, message):
    """Returns the bot's prefix.

    Args:
        bot (commands.AutoShardedBot): The bot object.
        message (discord.Message): Message object.

    Returns:
        str: The prefix the bot will accept.
    """
    return commands.when_mentioned_or(gp(message))(bot, message)

intents = discord.Intents.default()
intents.members = True
bot = commands.AutoShardedBot(command_prefix = get_prefix, case_insensitive = True, intents = intents)

# Load all of the custom prefixes into the "cache".
load_prefixes()

# Remove our help command
bot.remove_command("help")

# Loads all of our cogs.
for COG in Config.COGS:
    bot.load_extension(f"Cogs.{COG}")
    print(f"{Style.BRIGHT}{Fore.GREEN}[SUCCESS]{Fore.WHITE} Loaded Cog: {COG}")

async def owner(ctx):
    """Checks if a user is allowed to run the restart.
예제 #15
0
from conwech.functions import nameperiod, number2text
from discord.ext import commands, tasks
from math import *
import discord
import asyncio
import random
import requests
import datetime
import os
import pingus

# Hello! Welcome to the official GitHub repository of Greyson Bot.

client = commands.AutoShardedBot(command_prefix='G$',
                                 intents=discord.Intents.all())


@client.event
async def on_ready():
    print(f'Ready! {client.user}')
    await client.change_presence(activity=discord.Activity(
        name=
        f'my fabulousness to {len(client.guilds)} servers and {client.users} people.',
        type=discord.ActivityType.streaming))


@client.event
async def on_member_join(m):
    if m.guild.id == 828581824711753738:
        await asyncio.sleep(0.01)
        await m.add_roles(m.guild.get_role(828659697170907166))
예제 #16
0
import discord
import config
import aiohttp
import psutil
import traceback
import logging
from discord.ext import commands
from discord_slash import SlashCommand
logging.basicConfig(level=logging.INFO)

bot = commands.AutoShardedBot(
    command_prefix=commands.when_mentioned_or('sp!'),
    case_insensitive=True,
    case_insensitive_prefix=True,
    #allowed_mentions=discord.AllowedMentions.none(),
    max_messages=10000,
    intents=discord.Intents.all(),
    #    owner_ids=[698080201158033409, 443217277580738571],
    status=discord.Status.dnd,
    activity=discord.Activity(type=discord.ActivityType.playing,
                              name='sp!help'),
    description="A very cool discord bot for your server!")
slash = SlashCommand(client=bot,
                     sync_commands=True,
                     override_type=True,
                     sync_on_cog_reload=True)


@bot.event
async def on_ready():
    print(f'\n-= started successfully =-\n')
예제 #17
0
파일: run.py 프로젝트: zrawh2928/Sunny
        return ' '
    guildPref = None
    if message.guild:
        guildPref = mongoIO.getSetting(message.guild.id, 'prefix')
    if guildPref is not None:
        prefixes.append(guildPref)
    return commands.when_mentioned_or(*prefixes)(bot, message)


load_extensions = [
    'cogs.owner', 'cogs.admin', 'cogs.images', 'cogs.errorhandler', 'cogs.fun',
    'cogs.settings', 'cogs.information', 'cogs.osu', 'cogs.help', 'cogs.music'
]
bot = commands.AutoShardedBot(command_prefix=get_prefix,
                              description='Sunny Bot',
                              activity=discord.Streaming(
                                  name='#shameless_self_promotion',
                                  type=1,
                                  url='https://www.twitch.tv/niceaesthetic'))
bot.remove_command('help')

print(r"""
  .--.--.                                                  
 /  /    '.                                                
|  :  /`. /          ,--,      ,---,      ,---,            
;  |  |--`         ,'_ /|  ,-+-. /  | ,-+-. /  |           
|  :  ;_      .--. |  | : ,--.'|'   |,--.'|'   |     .--,  
 \  \    `. ,'_ /| :  . ||   |  ,"' |   |  ,"' |   /_ ./|  
  `----.   \|  ' | |  . .|   | /  | |   | /  | |, ' , ' :  
  __ \  \  ||  | ' |  | ||   | |  | |   | |  | /___/ \: |  
 /  /`--'  /:  | : ;  ; ||   | |  |/|   | |  |/ .  \  ' |  
'--'.     / '  :  `--'   \   | |--' |   | |--'   \  ;   :  
예제 #18
0
파일: run.py 프로젝트: driveru/Poll-Bot
import discord
from discord.ext import commands
import logging
import config
import aiohttp

logging.basicConfig(level=logging.INFO)
prefixes = ["+", "poll:", "Poll:", "POLL:"]
bot = commands.AutoShardedBot(
    command_prefix=prefixes,
    status=discord.Status.online,
    activity=discord.Game(name="+help"),
)
bot.remove_command("help")

extensions = ("cogs.poll", "cogs.strawpoll", "cogs.meta", "cogs.stats",
              "cogs.owner")


@bot.event
async def on_ready():
    bot.http_session = aiohttp.ClientSession()
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print("--------")


@bot.event
async def on_message(message):
    if not message.author.bot:
import discord
from discord.ext import commands
# functions.py
from config.bot.functions import *
# classes.py
from config.bot.classes import *
# window.py
from config.visual.window import *
# random
import random
# string
import string
# asyncio
import asyncio

client = commands.AutoShardedBot(command_prefix = GetBotPrefix(), intents = discord.Intents.all())

@client.event
async def on_ready():
    activity = discord.Activity(type=discord.ActivityType.watching, name="Captcha") 
    await client.change_presence(status=discord.Status.idle, activity=activity)
    printc(f">>> Game Setted Up to: {activity.name}", "green")
    printc(f">>> Shards: {client.shards}", "yellow")
    printc(">>> Bot is Ready!", "green")

@client.event
async def on_guild_channel_delete(channel):
    if GetSettingsValue(channel.guild.id, "logging") == channel.id:
        SetSettingsValue(channel.guild.id, "logging", "unknown")

@client.event
예제 #20
0
t_1_uptime = time.perf_counter()
guildlog = 400795084909576212
ownerlist = [304581891590324225, 289988391230242817]


def get_size(start_path='.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size


bot = commands.AutoShardedBot(command_prefix="*", description="Liam 2.0")
bot.remove_command("help")


@bot.event
async def on_guild_join(guild):
    servername = str(guild)
    chn = bot.get_channel(guildlog)
    await chn.send(
        content="[GUILD LOG] Joined {}, owned by {}#{}. Members = {}".format(
            servername, str(guild.owner.name), str(guild.owner.discriminator),
            len(guild.members)))


@bot.event
async def on_guild_remove(guild):
예제 #21
0
    while (shard_count % cluster_count) != 0:
        shard_count += 1
    print(f"Changed shard count to {str(shard_count)}")

step = shard_count / cluster_count
cluster_id -= 1
start = step * cluster_id
end = start + step

ushards = list(range(int(start), int(end)))

# Bot Initialization
if usesharding:
    bot = commands.AutoShardedBot(
        command_prefix="^^",
        pm_help=True,
        shard_ids=ushards,
        shard_count=shard_count,
        activity=discord.Game(name="Starting up bot..."))
else:
    print("No Sharding Activated")
    bot = commands.AutoShardedBot(command_prefix="^^")

setattr(bot, "GGL_KEY", "")

setattr(bot, "data", data)
setattr(bot, "loaded_modules", loadedmodules)

setattr(bot, "TEST_MODE", not usesharding)
setattr(bot, "CLUSTER_COUNT", cluster_count)
setattr(bot, "CLUSTER_ID", cluster_id)
setattr(bot, "SHARD_COUNT", shard_count)
예제 #22
0
report_channel_id = make_int(os.getenv("REPORT_CHANNEL_ID"))
suggest_channel_id = make_int(os.getenv("SUGGEST_CHANNEL_ID"))
dead_image_channel_id = make_int(os.getenv("DEAD_IMAGE_CHANNEL_ID"))
idol_post_send_limit = make_int(os.getenv("IDOL_POST_LIMIT"))

interaction_list = [
    'slap', 'kiss', 'lick', 'hug', 'punch', 'spit', 'pat', 'cuddle',
    'pullhair', 'choke', 'stepon', 'stab'
]

# client = commands.Bot(command_prefix=bot_prefix, case_insensitive=True, owner_id=owner_id)
intents = discord.Intents.default()
intents.members = True  # turn on privileged members intent
# intents.presences = True  # turn on presences intent
client = commands.AutoShardedBot(command_prefix=bot_prefix,
                                 case_insensitive=True,
                                 owner_id=owner_id,
                                 intents=intents)

# Reactions/Emotes


def get_emoji(string):
    if len(string) != 0:
        if string[0] == "<":
            return string
        else:
            string = chr(int(string, 16))
    return string


trash_emoji = get_emoji(os.getenv("TRASH_EMOJI"))
예제 #23
0
            await ctx.send(f"```\n{e}```")
            return
        await ctx.send(f"Loaded module **{name}**")

    @commands.command(no_pm=True)
    @commands.is_owner()
    async def modules(self, ctx):
        """Modules"""
        module_list = []
        for file in os.listdir("./modules"):
            if file.endswith(".py"):
                module_list.extend([f"{file}"[:-3]])
        await ctx.send("**" + "\n".join(module_list) + "**")


bot = commands.AutoShardedBot(command_prefix=prefix, description=description)


@bot.event
async def on_ready():
    print("Logged in as {0.id}/{0}".format(bot.user))
    print(f"{bot.shard_count}")
    print("----------")
    for file in os.listdir("modules"):
        if file.endswith(".py"):
            name = file[:-3]
            try:
                bot.load_extension(f"modules.{name}")
            except:
                channel = channel = bot.get_channel(log_channel_id)
                await channel.send(f"**{name}** failed to load! :warning:")
예제 #24
0
import discord
from discord.ext import commands
import strawpoll
import asyncio
import inflect
import json
import requests
import config
import collections

description = '''A bot that creates polls or strawpolls using discord'''

bot = commands.AutoShardedBot(command_prefix='+')

#Removes default help command

bot.remove_command("help")
c = collections.Counter()


#Log in
@bot.event
async def on_ready():
    await bot.change_presence(game=discord.Game(name='+help', type=0))
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('--------')
    if hasattr(bot, 'app'):
        return
    bot.app = await bot.application_info()
예제 #25
0
import yaml
import os
import traceback
import sys


async def get_prefix(client, message):
    try:
        with open(f'./Config/{message.guild.id}/guildSettings.yml', 'r', encoding='utf-8') as prefixes_cfg:
            prefixes = yaml.safe_load(prefixes_cfg)
            return commands.when_mentioned_or(*prefixes['PREFIX'])(client, message)
    except Exception as error:
        raise error


bot = commands.AutoShardedBot(command_prefix=get_prefix)

Converters.init(bot)
ModLogs.init(bot)


@bot.event
async def on_ready():
    # Инициализация БД
    await init_sql()
    print(f'[CORE] The bot is ready for duty!')
    await Log(log_data=':wave: Я уже работаю!').send(bot, Saber.MAIN_LOGS_CHANNEL)
    await bot.change_presence(activity=Saber.DEFAULT_STATUS)
    return print(f'[CORE] Logged in as {bot.user.name}#{bot.user.discriminator}')

예제 #26
0
            continue
        extension = extension[:-3]
        if not extension in cog_blacklist:
            try:
                bot.load_extension(f"cogs.{extension}")
                print(f"{extension}", end="; ")
            except discord.ext.commands.errors.ExtensionAlreadyLoaded:
                return
            except Exception as e:
                print()
                print(
                    f"[ERR] Failed to load extension {extension}. Reason: {e}")


bot = commands.AutoShardedBot(command_prefix=get_prefix,
                              fetch_offline_members=False,
                              max_messages=1000)
# bot.remove_command('help')


@bot.event
async def on_ready():
    print('[INFO] Using account {} with id {}'.format(bot.user.name,
                                                      bot.user.id))
    print("[INFO] Using discord.py version " + str(discord.__version__))
    print("Loaded plugins: ", end="")
    attach_cogs(bot)
    print()
    print(">>> Ready to play!")

예제 #27
0
파일: bot.py 프로젝트: Abood025/emojis
            # server doesn't have queue enabled; post the success message
            if success_message:
                embed = discord.Embed(title=success_message,
                                      colour=Colours.success,
                                      description=f"`:{emoji_json['title']}:`")

                embed.set_thumbnail(url=emoji_json["image"])

                # send
                await ctx.message.channel.send(embed=embed)

        return new_emoji


bot = commands.AutoShardedBot(command_prefix=get_prefix,
                              case_insensitive=True,
                              owner_ids=[554275447710548018])


@bot.event
async def on_message(message):
    """
    Check if the user pinged the bot; if they did, tell them the bot's prefix.
    """

    if message.content.startswith("<@!749301838859337799>"):
        prefix = get_prefix(bot, message)
        await message.channel.send(
            f"{message.author.mention}, this server's prefix is `{prefix}`. Try `{prefix}help`"
            f" to get started.")
예제 #28
0
파일: bot.py 프로젝트: CrepeSinner/SmexyBot
from utils import checks
from utils.language import Language

from discord.ext import commands
from utils.config import Config
from utils.tools import *
from utils.channel_logger import Channel_Logger
from utils.mysql import *
from utils.buildinfo import *

config = Config()
log.setupRotator(config.log_date_format, config.log_time_format)
if config.debug:
    log.enableDebugging()  # pls no flame
bot = commands.AutoShardedBot(
    command_prefix=config.command_prefix,
    description="A multi-purpose Ruby Rose from RWBY themed discord bot",
    pm_help=None)
channel_logger = Channel_Logger(bot)
aiosession = aiohttp.ClientSession(loop=bot.loop)
lock_status = config.lock_status

extensions = [
    "commands.fun", "commands.information", "commands.moderation",
    "commands.configuration", "commands.nsfw", "commands.music"
]

# Thy changelog
change_log = [
    "Commands:", "+ nou", "+ cow", "+ fortune", "+ cows", "+ neko", "+ twitch",
    "+ youtube", "+ owo", "Other things:",
    "The avatar command will now display png instead of webp for non-animated avatars",
예제 #29
0
파일: main.py 프로젝트: Kodikuu/Parsecbot
    print('Core data is missing.')

    token = input('Token: ')
    if token == '':
        raise ValueError('Invalid Token: Empty String')

    core = {
        'token': token,
    }
    del token  # We don't want extra auth token copies lying around.

    with open('core.private', 'x') as file:
        json.dump(core, file)

# Pre-start setup
bot = commands.AutoShardedBot(command_prefix=commands.when_mentioned_or('>'))
bot.activity = Activity(type=ActivityType.watching, name='Parsec develop.')
state = {
    'state': 'starting',
    'persistent': {},
    'client': bot,
    'ready_event': asyncio.Event(loop=bot.loop),
    'etime': 0,
    'erun': asyncio.Event(loop=bot.loop),
}

if path.exists('persistence.private') and path.isfile('persistence.private'):
    with open('persistence.private', 'r') as file:
        state['persistent'] = json.load(file)
        print('Loaded persistent data')
else:
예제 #30
0
TOKEN = cfg.TOKEN
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='discord.log',
                              encoding='utf-8',
                              mode='w')
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
handler.setLevel(logging.INFO)
logger.addHandler(handler)
bot = commands.AutoShardedBot(command_prefix='\\',
                              description=description,
                              intents=intents)
bot.last_message = dict()
bot.logger = logger
bot.logging_root = logging
bot.config = cfg
initial_extensions = [
    'cogs.admin', 'cogs.autoresponse', 'cogs.database', 'cogs.events',
    'cogs.general', 'cogs.schedevent', 'cogs.web', 'jishaku'
]

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)

bot.run(TOKEN)