Пример #1
0
def get_prefix(client, message):
    if message.guild is None or message.guild.id not in client.prefixes:
        return '!'
    else:
        return client.prefixes[message.guild.id]


logger = logging.getLogger('discord')
logger.setLevel(logging.WARNING)
handler = logging.FileHandler(
    filename=f'./logs/[{t.struct_time(t.gmtime())[0]}-{t.struct_time(t.gmtime())[1]}-{t.struct_time(t.gmtime())[2]}]-['
             f'{t.struct_time(t.gmtime())[3]}_{t.struct_time(t.gmtime())[4]}]-discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
client = customclient.CustomClient(
    DbMgr("db"), command_prefix=get_prefix, intents=Intents.all(), case_insensitive=True)


def load_modules():
    # Module beim Botstart laden
    for filename in os.listdir('./cogs'):
        if filename.endswith(".py"):
            if not filename.startswith('test'):
                client.load_extension(f'cogs.{filename[:-3]}')
                print(filename[:-3] + ' aktiviert')
        elif filename.endswith('__pycache__'):
            print('Py-Cache gefunden')
        else:
            print('\x1b[6;30;42m' + f"Fehlerhafte File auf dem Server gefunden! {filename}" + '\x1b[0m')
    print('Module geladen')
Пример #2
0
from discord import Intents
from discord.ext.commands import Bot
from importlib import import_module
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

bot = Bot(
    command_prefix=settings.DISCORD_BOT_PREFIX,
    case_insensitive=True,
    description=settings.DISCORD_BOT_DESCRIPTION,
    intents=Intents.all(),
)

for app in settings.INSTALLED_APPS:
    app_name, *_ = app.split(".apps")

    # skip modules without cogs
    try:
        loaded_cog = import_module(f'{app_name}.cogs')
    except ModuleNotFoundError:
        continue

    if '__all__' not in dir(loaded_cog):
        logger.warning(f"Unable to load cog {app_name}: __app__ not found!")
        continue

    # TODO possible security vulnerability: find solution without eval() / exec()!
    for cog in loaded_cog.__all__:
        exec(f'from {app_name}.cogs import {cog}')
Пример #3
0
import discord
from discord import Client, Intents
from discord.utils import get
from decouple import config

from discord.ext import commands
from discord.ext.commands import Bot

from .core.api import CEMIT
from .core.errors import MemberExists, MemberNotFound

# Permissions bot
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='>', intents=intents)

cemit = CEMIT()

CHANNEL_MAP = {'bot': '🤖cemit-discord-bot', 'valid': '✅validation'}


@bot.command()
async def validate(ctx, user_id):
    if ctx.channel.name == CHANNEL_MAP['valid']:
        """
        TODO: 
            - Check id in DB
            - Check if already validated
        """
        try:
            cemit.validate_member(user_id)
Пример #4
0
from aiohttp import ClientSession
from discord import Intents, Status, Activity
from discord.ext.commands import Bot
from .utils.meta import BOT_PREFIX
from .helpers.auth import getenv
from .helpers.extensions import load_ext

intents = Intents(
    guilds=True,
    members=True,
    emojis=True,
    voice_states=True,
    guild_messages=True,
    guild_reactions=True,
)


class TheBot(Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.loop.create_task(self.sessionify())

    async def sessionify(self):
        self.ses = ClientSession()

    async def close(self):
        await self.ses.close()
        await super().close()

    async def fetch_json(self, url, *, method="get", session=None, **kwargs):
        async with (session or self.ses).request(method, url, **kwargs) as resp:
Пример #5
0
    def get_intents(self):
        intents = Intents.default()
        intents.members, intents.presences = True, True

        return intents
Пример #6
0
# # attributes.py, Created by Janrey "CodexLink" Licas
# ! A set of attributes to pass on Entrpoint's Constructor to Instantiate Discord Bot and other Subclasses.
# * Seperated for Code Clarity and Focused Environment specifically for Entrypoint.

from collections import namedtuple
from discord import Activity, Intents, CustomActivity, PartialEmoji
from .constants import RP_ATTRS_DEFAULT
from datetime import datetime as dt
"""
# Bot's Intents

* I'm not gonna use default()'s intents. But rather, have to declare them
* on my own. This was done to properly include 'only' important features of the bot.
"""

attr_intents = Intents.none()

attr_intents.bans = True  # Has the right to ban people from manipulating the bot.
attr_intents.emojis = False  # Has no access to emojis for reacts in general.
attr_intents.invites = True  # Disallow people from inviting this bot because it doesn't make any difference.
attr_intents.messages = False  # Has no access to messages for reacts in general.
attr_intents.presences = True  # Has access to presence for presence record to Firebase.
attr_intents.dm_messages = True  # Has access to Direct Message, specifically.
attr_intents.dm_reactions = (
    True  # Has access to Direct Message Reactions, specifically.
)
"""
# Bot's Presence Activity

* All Possible Configurations were Added.
! But not all of them will be displayed since it was a bot who uses it.
Пример #7
0
            return wrapper

        return decorator

    @staticmethod
    def flags(fn):
        fn.__flags__ = True
        return fn

    Permissions = Permissions.Permissions  # pylint: disable=no-member

    def __repr__(self):
        return "< Bloxlink Client >"


intents = Intents.none()

intents.members = True  # pylint: disable=assigning-non-slot
intents.guilds = True  # pylint: disable=assigning-non-slot
intents.guild_reactions = True  # pylint: disable=assigning-non-slot
intents.guild_messages = True  # pylint: disable=assigning-non-slot
intents.dm_messages = True  # pylint: disable=assigning-non-slot
intents.bans = True  # pylint: disable=assigning-non-slot

if RELEASE == "PRO":
    intents.guild_typing = True  # pylint: disable=assigning-non-slot

Bloxlink = BloxlinkStructure(
    chunk_guilds_at_startup=False,
    shard_count=SHARD_COUNT,
    shard_ids=SHARD_RANGE,
Пример #8
0
import os
import traceback

import discord
from discord import Intents
from discord.ext.commands import Bot, when_mentioned_or

# Importing the newly installed library.
from discord_slash import SlashCommand

from slashtilities import background, cogs, log, utils, settings, DB_ENABLED

TOKEN = os.environ["DISCORD_TOKEN"]
intents = Intents().default()

bot = Bot(when_mentioned_or("/"), intents=intents)
slash = SlashCommand(bot, sync_commands=True)

# TODO: listeners.py
@bot.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.user_id == bot.user.id:
        return
    message = await bot.get_channel(payload.channel_id).fetch_message(
        payload.message_id
    )
    reactions = message.reactions

    # Check if reacting to a message a bot has reacted to
    if not any(other_reactions.me for other_reactions in reactions):
        return
Пример #9
0
"""Music bot for Discord that can be controlled via websockets"""

__version__ = "1.1.1"
__author__ = "Dominic Bowden"
__copyright__ = "2018, Dominic Bowden"
__license__ = "ISC"
__url__ = "https://github.com/tedle/uitabot"

from discord import Client, Intents
from uita.ui_server import Server
from uita.types import DiscordState
import asyncio

# Use a bunch of globals because of decorator class methods
loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
bot: Client = Client(
    loop=loop,
    intents=Intents(
        guilds=True,  # List which guilds bot is in
        members=True,  # Web UI verification of user permissions
        voice_states=True,  # Auto-pause when voice channel is empty
        guild_messages=True,  # Chat commands
        guild_reactions=True  # Chat command UI
    ))
server: Server = Server()
state: DiscordState = DiscordState()

# Initialize bot and server decorators
import uita.bot_events, uita.server_events  # noqa: E401,E402,F401
Пример #10
0
from templatebot import Bot
from discord import Intents
from os import getenv
from botconfig.client import BotConfig
from discord.ext.commands import MinimalHelpCommand

intents = Intents.none()
intents.voice_states = True
intents.messages = True
intents.guilds = True

bot = Bot(
    name="Airhorn Supremacy",
    command_prefix="ah!",
    intents=Intents.default(),
    logging_url=getenv("WEBHOOK"),
    help_command=MinimalHelpCommand(),
)
bot.config = BotConfig(getenv("BOT_ID"), getenv("CONFIG_TOKEN"))

bot.load_initial_cogs("cogs.airhorn", "cogs.config")

bot.run(getenv("TOKEN"))
Пример #11
0
    Bot,
    Context,
    ExtensionAlreadyLoaded,
    ExtensionFailed,
    ExtensionNotFound,
    NoEntryPointError,
)
import os
from pathlib import Path

from . import logger, commands

logger.initialize()

# Initialize the bot
intents = Intents(guilds=True, members=True, messages=True, reactions=True)
bot = Bot(command_prefix="-", intents=intents, help_command=commands.Help())
bot.on_command_error = commands.on_error


# Block DMs globally
@bot.check
async def block_dms_globally(ctx: Context):
    return ctx.guild is not None


# Dynamically load extensions
extension_logger = logger.get("extensions")
extensions_path = Path(__file__).parent.joinpath("extensions")
for path in os.listdir(extensions_path):
    potential_import = extensions_path.joinpath(path)
Пример #12
0
    "app.cogs.base.base_events",
    "app.cogs.starboard.starboard_commands",
    "app.cogs.starboard.starboard_events",
    "app.cogs.owner.eval",
    "app.cogs.owner.owner_commands",
    "app.cogs.cache.cache_events",
    "app.cogs.settings.settings_commands",
    "app.cogs.utility.utility_commands",
    "app.cogs.fun.fun_commands",
    "app.cogs.quick_actions.qa_events",
    "app.cogs.stats.stats_events",
    "jishaku",
]
INTENTS = Intents(messages=True,
                  guilds=True,
                  emojis=True,
                  reactions=True,
                  members=True)
NO_MENTIONS = AllowedMentions.none()
SHARDS = config.SHARDS

log = logging.getLogger("Cluster#Launcher")
log.setLevel(logging.DEBUG)
hdlr = logging.StreamHandler()
hdlr.setFormatter(
    logging.Formatter("[%(asctime)s %(name)s/%(levelname)s] %(message)s"))
fhdlr = logging.FileHandler("logs/cluster-Launcher.log", encoding="utf-8")
fhdlr.setFormatter(
    logging.Formatter("[%(asctime)s %(name)s/%(levelname)s] %(message)s"))
log.handlers = [hdlr, fhdlr]
Пример #13
0
        self.load_cogs()

    def load_cogs(self):
        cogs_dir = Path("./cogs/")
        for cog in cogs_dir.glob("*.py"):
            cog_name = "cogs." + str(cog).split("/")[-1][:-3]
            try:
                self.unload_extension(cog_name)
            except:
                pass
            try:
                self.load_extension(cog_name)
                self.logger.debug(f"Loaded cog {cog_name}")
            except Exception as e:
                self.logger.error("A error occurred while loading a cog",
                                  exc_info=e)


def get_prefix(_bot: Bot, message: Message):
    api = _bot.get_cog("Api")
    guild_config = api.get_server_settings(message.guild)
    if guild_config is None:
        return DEFAULT_PREFIX
    return guild_config.get("prefix", DEFAULT_PREFIX)


intents = Intents(guilds=True, voice_states=True, messages=True)
if __name__ == "__main__":
    bot = Bot(get_prefix, intents=intents)
    bot.run(BOT_TOKEN)
Пример #14
0
import functools
import random
import re

import markovify
import toml

from discord import AllowedMentions, Client, Intents
from discord.ext import commands

ALLOWED_MENTIONS = AllowedMentions.none()
INTENTS = Intents(emojis=True, guilds=True, messages=True)

EMOJI_REGEX = re.compile(
    "<(?P<animated>a?):(?P<name>[a-zA-Z0-9_]{2,32}):(?P<id>[0-9]{18,22})>")
CHANNEL_REGEX = re.compile("<#([0-9]*)>")
USER_MENTION = re.compile("<@(!?)([0-9]*)>|@[a-zA-Z0-9_]*")

with open("config.toml", "r", encoding="utf-8", errors="ignore") as toml_file:
    CONFIG = toml.load(toml_file)

with open("markov.txt", "r", encoding="utf-8", errors="ignore") as markov_file:
    model = markovify.NewlineText(markov_file.read(),
                                  state_size=5,
                                  retain_original=False)
    model.compile(inplace=True)


class Chatstero(Client):
    def __init__(self):
        super().__init__(allowed_mentions=ALLOWED_MENTIONS, intents=INTENTS)
Пример #15
0
import constants
from bot import Bot

root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(message)s")
console = logging.StreamHandler(stdout)
console.setFormatter(formatter)
root_logger.addHandler(console)

root_logger.info(f"Running as main bot.")

if __name__ == "__main__":
    load_dotenv()
    bot = Bot(case_insensitive=True, intents=Intents.all())
    for extension_path in Path("./cogs").glob("*.py"):
        extension_name = extension_path.stem
        if extension_name in constants.ignored_extensions:
            continue

        dotted_path = f"cogs.{extension_name}"
        try:
            bot.load_extension(dotted_path)
            root_logger.info(f"loaded {dotted_path}")
        except Exception as e:
            traceback_msg = traceback.format_exception(etype=type(e),
                                                       value=e,
                                                       tb=e.__traceback__)
            root_logger.info(
                f"Failed to load cog {dotted_path} - traceback:{traceback_msg}"
Пример #16
0
    args = {
        "command_prefix":
        prefix_callable,
        "case_insensitive":
        True,
        "max_messages":
        None,
        "intents":
        Intents(
            guilds=True,
            members=True,
            bans=True,
            emojis=True,
            integrations=False,
            webhooks=False,
            invites=False,
            voice_states=True,
            presences=False,
            messages=True,
            reactions=True,
            typing=False,
        ),
        "member_cache_flags":
        MemberCacheFlags(
            online=False,
            voice=True,
            joined=True,
        ),
        "chunk_guilds_at_startup":
        False
    }
Пример #17
0
            return load(stored_config)

    def save_configuration(self) -> None:
        if not self.config == self.last_saved_config:
            with open("./data/serverconfig.json", "w") as stored_config:
                # This writes the configuration with the changes made to the disk.
                dump(self.config, stored_config, indent=4)
                stored_config.truncate()

    @tasks.loop(minutes=1.0)
    async def config_daemon(self):
        self.save_configuration()
        self.last_saved_config = copy(self.config)


admin = AdminBot(command_prefix="-", intents=Intents.all())


@admin.command(
    description=
    "Reloads the specified module, or all of them if no module is specified.")
@commands.is_owner()
async def reload(ctx: commands.Context, module_name=None):
    if module_name is None:

        active_modules = [extension for extension in admin.extensions]

        for module_title in active_modules:
            admin.unload_extension(module_title)

        for module_title in listdir("./modules"):
Пример #18
0
 def __init__(self):
     super().__init__(command_prefix="//", intents=Intents.all())
     super().remove_command("help")
     self._TOKEN = TOKEN
Пример #19
0
 def __init__(self):
     super().__init__(Intents.all())
     self.add_cog(DBLStatsExtension(self))
Пример #20
0
 def __init__(self, commands_prefix: str):
     intents = Intents.default()
     intents.members = True
     intents.presences = True
     intents.reactions = True
     super().__init__(command_prefix=commands_prefix, intents=intents)
Пример #21
0
import os

from discord import Intents
from basedbot import DBot


# Find server prefix
def get_prefix(bot, message):
    if message.guild is None:
        return '!'

    return bot.conf.get(message.guild.id, 'prefix')


bot = DBot(command_prefix=get_prefix, intents=Intents.all())
bot.conf.register('prefix',
                  default='!',
                  description="The command prefix that the bot reacts to.")

bot.add_cog_path('cogs')
bot.add_cog_path('cogs/legacy')

bot.db.add_sql_path('sql')

# Load all modules
for cog in bot.find_all_cogs():
    try:
        bot.load_extension(cog)
    except Exception as e:
        print(f"Exception while loading `{cog}`:")
Пример #22
0
from discord import Intents

bot_token: str = ""
command_prefixes: list = ["!", "!!"]

discord_intents: Intents = Intents.all()

mongodb_options: dict = {
    "host": "localhost",
    "port": 27017,
    "database_name": "discord_bot"
}
Пример #23
0
from token_storage import token

POST_ID = 817054917415796776

CHANNEL_TO_SPREAD_ID = 817050403484336132

ROLES = {
    '1️⃣': 817056742697336882,
    '2️⃣': 817057140535590942,
    '3️⃣': 817057299558039582,
    '4': 830359760393601044
}

BLACK_LIST = ['привет', 'пока', 'каркас', 'чижи']

client = discord.Client(intents=Intents.all())


@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    # role = message.guild.get_role(820240223506006058)
    # await role.delete()
Пример #24
0
 def __init__(self):
     super().__init__(
         command_prefix=["/"],
         help_command=None,
         intents=Intents.all(),
     )
Пример #25
0
import os
import json

from discord_slash import SlashCommand
from discord.ext import commands
from discord import Intents

bot = commands.Bot(command_prefix="!", intents=Intents.all())
slash = SlashCommand(bot, override_type=True, sync_commands=True)

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

with open("configs/configBot.json") as f:
    bot.run(json.load(f)["token"])
Пример #26
0
import datetime

from discord.ext import commands
from discord import Embed, Intents

from app.users import COUNT_TO_A_MILLION_ID, TEST_CHANNEL_ID, BOT_ID

bot = commands.Bot(command_prefix="!", case_insensitive=True,  intents=Intents.all())


async def send_message_if_applicable(ctx, msg):
    if not msg:
        return
    message = ctx.message
    messages_to_send = [msg[i:i+2000] for i in range(0, len(msg), 2000)]
    for m in messages_to_send:
        await send_message_to_channel_if_applicable(message, m)

async def send_message_to_channel_if_applicable(message, msg, embed=False):
    channel = message.channel
    if channel.id in [COUNT_TO_A_MILLION_ID]:
        messages = await channel.history(limit=1000).flatten()
        messages = list(filter(lambda x: x.author.id == BOT_ID, messages))
        if messages:
            my_last_message = messages[0]
            current_time = datetime.datetime.now()
            my_last_message_time = my_last_message.created_at
            time_difference = current_time - my_last_message_time
            if time_difference.days < 1:
                return
Пример #27
0
logger = get_logger(__name__)

t = t.g


async def fetch_prefix(_, msg: Message) -> Iterable[str]:
    prefix = [await get_prefix(), f"<@!{bot.user.id}> ", f"<@{bot.user.id}> "]

    if msg.guild is None:
        prefix.append("")

    return prefix


bot = Bot(command_prefix=fetch_prefix, case_insensitive=True, intents=(Intents.all()))
bot.remove_command("help")


@listener
async def on_ready():
    logger.info(f"\033[1m\033[36mLogged in as {bot.user}\033[0m")


@bot.event
async def on_error(*_, **__):
    sentry_sdk.capture_exception()
    raise  # skipcq: PYL-E0704


@listener
Пример #28
0
"""
Python Discord Bot(Z-Bot)
Developer: CamoMano
This is a simple Discord bot written in Python 3.7
"""

import feedparser
import discord
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext

# Sets the command prefix
client = discord.Client(intents=Intents.default())
slash = SlashCommand(client, sync_commands=True)

# Opens key.txt where the bot key is stored
keyfile = open("key.txt", "r")

# Reads the file and sets the key
key = keyfile.read()

# Closes the file
keyfile.close()


# Shows that the bot has logged in
@client.event
async def on_ready():
    print("--------------------")
    print("Successfully logged in as")
    print(client.user.name)
Пример #29
0
import discord
from discord.ext import commands
from discord import Intents
import random
import time
client = commands.Bot(command_prefix = '!', intents = Intents.all()) # установка префикса для команд и намерений бота (то, с чем он может взаимодействовать), discord.Intents - класс,
																	 # отвечающий за область действия бота (намерения)

client.remove_command('help') # удаление дефолтной команды !help для ее последующей замены,
# class discord.client класс discord.py, представляющий собой клиентское соединение, которое подключается к Discord


@client.command(pass_context = True) # pass_context = True - разрешает команде использовать контекст
async def roles_help(ctx):
	'''
	функция для показа возможных к получению ролей
	аргумент ctx - контекст
	class discord.Embed - класс discord.py, отвечающий за embed'ы (другой способ красивого вывода текста)
	class discord.Color - стандартная библиотека цветов discord.py
	class discord.client - класс discord.py, представляющий собой клиентское соединение, которое подключается к Discord
	'''
	roles_ch = client.get_channel(778260081879416842)
	emb = discord.Embed(title = 'Роли', colour = discord.Color.green()) # создание Embed
	emb.add_field(name = 'WoW', value = '"!roles 1" - для получения роли WoW и доступа к закрытым каналам игры (код - 1)', inline = False)
	emb.add_field(name = 'SC2', value = '"!roles 2" - для получения роли SC2 и доступа к каналам (код - 2)', inline = False)
	emb.add_field(name = 'Python', value = '"!roles 3" - для получения роли Python и доступа к канал для программистов (код - 3)', inline = False)
	emb.add_field(name = 'Java', value = '"!role 4" - для получения роли Java и доступа к каналам (код - 4)', inline = False)
	emb.add_field(name = 'Комбинации ролей', value = 'Например, "!roles 1234" - выдаст все доступные пока что роли', inline = False)
	await roles_ch.send(embed = emb)
Пример #30
0
# BOTRADICAL IS A BOT FRAMEWORK DESIGNED BY NASHRADICAL
# ORIGINALLY DESIGNED FOR "EDEN NETWORK" AND "THE COSMOS"
# THIS FRAMEWORK IS FREE TO USE AND MODIFY

# DISCORD: "nashradical#1111"
# GITHUB: "https://github.com/nashradical"

from discord import Intents
from os import listdir
from discord.ext import commands
from modules.ext import console, embed_help
from modules.config import base, core

console.log('Starting Bot...')

intents = Intents.all()  # subscribe to all discord intents
bot = commands.Bot(
    command_prefix=core.get['prefix'],
    case_insensitive=True,
    help_command=embed_help(
    ),  # replace default help command with modules/ext/help.py
    intents=intents)

console.log('Loading Cogs...')

for filename in listdir('./modules/cogs'):
    bot.load_extension('modules.cogs.' + filename)
    print('           | Loaded ' + filename)
bot.load_extension('modules.start')

console.log('Connecting to Discord...')