コード例 #1
0
ファイル: pom_wars.py プロジェクト: mukkuzzz/pom-bot
def setup(bot: Bot):
    """Load Pom Wars commands.

    Do not use this to add event handlers as basic and essential debugging
    and logging will be broken. Instead, add them in bot.main.
    """
    for command in [
            BotCommand(commands.do_actions, name="actions"),
            BotCommand(commands.do_attack, name="attack"),
            BotCommand(commands.do_bribe, name="bribe", hidden=True),
            BotCommand(commands.do_defend, name="defend"),
    ]:
        bot.add_command(command)
コード例 #2
0
async def getUser(bot: Bot, id):
    user = bot.get_user(id)

    if not user:
        user = await bot.fetch_user(id)

    return user
コード例 #3
0
async def getGuild(bot: Bot, id):
    guild = bot.get_guild(id)

    if not guild:
        guild = await bot.fetch_guild(id)

    return guild
コード例 #4
0
def format_warn(warn: drop.types.Warn, bot: Bot):
    warner_id = warn.warner.id
    warner_user = bot.get_user(id=warner_id)
    if not warner_user:
        warner_display = f"{warn.warner.name} (<@{warner_id}>)"
    else:
        warner_display = f"<@{warner_id}>"
    return f"""
コード例 #5
0
    async def on_call(self, channel: channel, ctx: Context, bot: Bot,
                      args: list, globals: list, plugins: Container) -> None:
        channel = ctx.channel
        if ctx.author not in admins:
            await channel.send(
                f"Sorry, you have no permission to execute this command")
            return
        try:
            if args[0] == 'help':
                helpdoc = HelpDoc(self.prefix)
                helpdoc.add('load <module_name>')
                helpdoc.add('unload <module_name>')
                helpdoc.add('post <channel_id> <information>')
                helpdoc.add('stop')
                helpdoc.add('plugins')
                await channel.send(str(helpdoc))
            # elif args[0] == 'test':
            #     await channel.send(f"ctx: {globals['raw_ctx'].author.id}")
            elif args[0] == 'post':
                if args[1] == 'help':
                    await channel.send(f"`post <channel_id> <information>`")
                try:
                    int(args[1])
                    if int(args[1]) != eval(args[1]):
                        return
                except:
                    return
                try:
                    channel = bot.get_channel(int(args[1]))
                    await channel.send(args[2])
                except:
                    pass
            elif args[0] == 'load':
                try:
                    if len(args) != 2:
                        await channel.send(f"`load <module_name>`")
                    elif plugins.load(args[1]):
                        await channel.send(f"Successfully loaded {args[1]}")
                    else:
                        await channel.send(f"Failed to load {args[1]}")
                except Exception as exc:
                    await channel.send(f"Failed to load {args[1]} ({exc})")
            elif args[0] == 'unload':
                if len(args) != 2:
                    await channel.send(f'`unload <module_name>`')
                elif args[1] not in plugins.list():
                    await channel.send(f'Module "{args[1]}" is not loaded')
                else:
                    plugins.unload(args[1])
            elif args[0] == 'plugins':
                await channel.send(plugins.info())

            elif args[0] == 'stop':
                await channel.send(f"Server Manager is offline")
                sys.exit(0)

        except IndexError:
            pass
コード例 #6
0
async def getChannel(bot: Bot, id):
    channel = bot.get_channel(id)

    if not channel:
        try:
            channel = await bot.fetch_channel(id)
        except discord.InvalidData:
            channel = None
        except discord.HTTPException:
            channel = None

    return channel
コード例 #7
0
async def _write_to_channel(bot: Bot,
                            channel_id: int = 0,
                            message=None,
                            channel_type: str = ""):
    """
    Writes a message to a channel and logs the message

    :param bot: The bot
    :param channel_id: The channel ID of the channel to send a message to
    :param message: The message or embed to send
    :param channel_type: The channel type or name for the logging output
    """

    channel = bot.get_channel(channel_id)
    if not Config(
    ).DEBUG_MODE and channel is not None and message is not None and message:
        if isinstance(message, discord.Embed):
            await channel.send(embed=message)
        else:
            await channel.send(message)

    log_msg = get_loggable_str(message)
    chan_logger.info(f"{channel_type} : {log_msg}")
コード例 #8
0
def setup(bot: Bot):
    # importlib.reload(Event)
    importlib.reload(cfg)
    bot.add_cog(CommandListener(bot))
コード例 #9
0
ファイル: manageable.py プロジェクト: scytail/Manageable
from discord.ext.commands.bot import Bot
from discord import Intents
import Code.Cogs.Base as Base
from Code.Cogs.ModToolsCogs import UserWarnCog, AutoDrawingPrompt
from Code.Cogs.MessagingCogs import HelpCog, TagCog, CookieHuntCog, DiceRollerCog
from Code.Cogs.SystemInteractionCogs import GlobalErrorHandlingCog, RoleRequestCog, AirlockCog

if __name__ == '__main__':
    # Build the bot
    Base.ConfiguredCog.logger.info('Constructing Manageable bot...')
    Base.ConfiguredCog.logger.debug(f'Building bot.')

    intents = Intents.default()
    intents.members = True  # Among others, the help command needs the members intent to monitor reactions

    discord_bot = Bot(Base.ConfiguredCog.config['command_prefix'],
                      intents=intents)

    Base.ConfiguredCog.logger.debug('Removing built-in help command.')
    discord_bot.remove_command('help')  # We are providing our own help command

    # Add the necessary cogs
    Base.ConfiguredCog.logger.info('Attaching functionality...')

    # Do not disable
    Base.ConfiguredCog.logger.debug('Adding GlobalErrorHandling Cog.')
    discord_bot.add_cog(GlobalErrorHandlingCog(discord_bot))

    # Do not disable
    Base.ConfiguredCog.logger.debug('Adding Help Cog.')
    discord_bot.add_cog(HelpCog(discord_bot))
コード例 #10
0
ファイル: __init__.py プロジェクト: AchielC/plopkoek-discord
def setup(bot: Bot):
    bot.add_cog(PlopkoekCog(bot))
コード例 #11
0
        await ctx.send(" 누구를 언밴할 거냐고, 이 쓸모없는 쓰레기야! ")


@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingAnyRole):
        await ctx.send("{} 넌 권한이 없다, 이 쓸모없는 쓰레기야! ".format(ctx.message.author))


@mute.error
async def mute_error(ctx, error):
    if isinstance(error, commands.MissingAnyRole):
        await ctx.send("{} 넌 권한이 없다, 이 느끼한 느림보야! ".format(ctx.message.author))
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(" 누구를 뮤트할 건지 쓰라고, 이 풋풋한 풋내기야! ")
    if isinstance(error, commands.BadArgument):
        await ctx.send(" 누구를 뮤트할 거냐고, 이 멍청한 멍청아! ")


@unmute.error
async def unmute_error(ctx, error):
    if isinstance(error, commands.MissingAnyRole):
        await ctx.send("{} 넌 권한이 없다, 이 느끼한 느림보야! ".format(ctx.message.author))
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(" 누구를 언뮤트할 건지 쓰라고, 이 고환 없는 고자야! ")
    if isinstance(error, commands.BadArgument):
        await ctx.send(" 누구를 언뮤트할 거냐고, 이 거대한 거위야! ")


Bot.run(os.environ['token'])
コード例 #12
0
from discord.ext.commands.bot import Bot
from discord import Message, TextChannel, Webhook, AsyncWebhookAdapter
from os import getenv
import aiohttp

bot = Bot("m!")

quote_wall_id = 692999924349927514
webhook_url = getenv("WEBHOOK_URL")
bot_token = getenv("BOT_TOKEN")


@bot.event
async def on_ready():
    print("I'm awake now")


@bot.event
async def on_message(message: Message):
    async with aiohttp.ClientSession() as session:
        target_webhook = Webhook.from_url(webhook_url,
                                          adapter=AsyncWebhookAdapter(session))
        if message.channel.id == quote_wall_id:
            await target_webhook.send(
                message.content,
                username=message.author.display_name,
                avatar_url=message.author.avatar_url,
                files=[
                    await file.to_file(spoiler=file.is_spoiler())
                    for file in message.attachments
                ])
コード例 #13
0
ファイル: __main__.py プロジェクト: tripulse/boileur
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.

import logging

from discord import Intents
from discord.ext.commands.bot import Bot, when_mentioned

from os import environ

if __name__ == '__main__':
    logging.basicConfig(format='[%(levelname)s] %(name)s: %(message)s', level=logging.INFO)
    
    opts = Intents(messages=True, guilds=True)
    bot = Bot(when_mentioned, case_insensitive=True, intents=opts)
    bot.logger = logging.getLogger()

    bot.load_extension('cogs')

    try:
        bot.run(environ['DISCORD_TOKEN'])
    except KeyError:
        print('Token for accessing Discord API was not given')
コード例 #14
0
def setup(client: Bot) -> None:
    """
    Loads the Search cog.
    """
    client.add_cog(Search(client))
コード例 #15
0
def setup(client: Bot) -> None:
    """
    Loads the Social cog.
    """
    client.add_cog(Social(client))
コード例 #16
0
def setup(bot: Bot):
    """Required to load extension."""
    bot.add_cog(AdminCommands(bot))
コード例 #17
0
ファイル: echo.py プロジェクト: AchielC/plopkoek-discord
def setup(bot: Bot):
    bot.add_cog(EchoCog(bot))
コード例 #18
0
ファイル: __init__.py プロジェクト: NikcraftHD/Geckarbot
async def write_debug_channel(bot:Bot, message):
    """Writes the given message to the bot's debug channel"""
    debug_chan = bot.get_channel(DEBUG_CHAN_ID)
    if(debug_chan != None):
        await debug_chan.send(message)
コード例 #19
0
ファイル: quote.py プロジェクト: AchielC/plopkoek-discord
def setup(bot: Bot):
    bot.add_cog(QuoteCog(bot))
コード例 #20
0
ファイル: __init__.py プロジェクト: devspacemx/centinela
def init(bot: Bot):
    bot.add_cog(MemberJoin(bot))
    bot.add_cog(OnReady(bot))
    bot.add_cog(CommandError(bot))
    bot.add_cog(OnGuildRemove(bot))
    bot.add_cog(OnRawReactionAdd(bot))
    bot.add_cog(OnRawReactionRemove(bot))
コード例 #21
0
ファイル: ping.py プロジェクト: jay214421343/DiscordBdBot
def setup(bot: Bot, kwargs: Dict[Any, Any]) -> None:
    bot.add_cog(Ping(bot, **kwargs))
コード例 #22
0
ファイル: stats.py プロジェクト: jay214421343/DiscordBdBot
def setup(bot: Bot, kwargs: Dict[str, Session]) -> None:
    bot.add_cog(Stats(bot, **kwargs))
コード例 #23
0
def setup(client: Bot) -> None:
    """
    Loads the Miscellaneous cog.
    """
    client.add_cog(Miscellaneous(client))
コード例 #24
0
def setup(bot: Bot, kwargs: Dict[str, Session]) -> None:
    bot.add_cog(EventCmd(bot, **kwargs))
コード例 #25
0
ファイル: __init__.py プロジェクト: devspacemx/centinela
def init(bot: Bot):
    bot.add_cog(Help(bot))
    bot.add_cog(Version(bot))
    bot.add_cog(Activity(bot))
    bot.add_cog(WelcomeChannel(bot))
    bot.add_cog(AdminList(bot))
    bot.add_cog(ActivityList(bot))
    bot.add_cog(AddAdmin(bot))
    bot.add_cog(Colour(bot))
    bot.add_cog(Kill(bot))
    bot.add_cog(SystemChannel(bot))
    bot.add_cog(New(bot))
    bot.add_cog(Notify(bot))
    bot.add_cog(Edit(bot))
    bot.add_cog(Reaction(bot))
    bot.add_cog(RemoveAdmin(bot))
    bot.add_cog(Restart(bot))
    bot.add_cog(RemoveActivity(bot))
    bot.add_cog(SetStarterRole(bot))
コード例 #26
0
def get_prefix(bot: Bot, message: Message):
    preferences_cog = bot.get_cog('Preferences')
    return preferences_cog.scoped_property_manager.get('prefix', message.channel)
コード例 #27
0
ファイル: bot.py プロジェクト: Wihrt/discord_against_humanity
from logging.config import dictConfig
from logging import getLogger, Formatter, FileHandler, StreamHandler, info, critical, INFO
from os import environ
from sys import stdout
from traceback import print_tb
from json import load

from discord import Color
from discord.ext.commands import errors
from discord.ext.commands.bot import Bot
from pymongo import MongoClient
from motor.motor_asyncio import AsyncIOMotorClient

from utils.embed import create_embed

BOT = Bot(command_prefix="$", pm_help=False)  # Create the bot
BOT.mongo = AsyncIOMotorClient(host=environ["MONGO_HOST"], port=int(environ["MONGO_PORT"]),
                               connect=True)

# Extensions to load at start
LOGGER = getLogger("discord_against_humanity.bot")
EXTENSIONS = ["commands.discord_against_humanity"]


def init_logger():
    """Set the logger to the desired level

    Keyword Arguments:
        level {int} -- Level of logging (default: {INFO})
    """
    with open("logging.json", "r") as config_file: