コード例 #1
0
ファイル: bot.py プロジェクト: DenverCoder1/dev-pro-tips-bot
def main():
    # allows privledged intents for monitoring members joining, roles editing, and role assignments
    intents = nextcord.Intents.default()
    intents.guilds = True
    intents.members = True
    intents.message_content = True

    activity = nextcord.Activity(type=nextcord.ActivityType.listening,
                                 name=f"{config.PREFIX}help")

    bot = commands.Bot(
        command_prefix=commands.when_mentioned_or(config.PREFIX),
        intents=intents,
        activity=activity,
        owner_id=config.OWNER_ID,
    )

    # boolean that will be set to true when views are added
    bot.persistent_views_added = False

    @bot.event
    async def on_ready():
        print(f"{bot.user.name} has connected to Discord.")

    # load all cogs
    for folder in os.listdir("cogs"):
        bot.load_extension(f"cogs.{folder}")

    async def startup():
        bot.session = aiohttp.ClientSession()

    bot.loop.create_task(startup())

    # run the bot
    bot.run(config.BOT_TOKEN)
コード例 #2
0
def main():
    client = commands.Bot(command_prefix="?")

    load_dotenv()

    @client.event
    async def on_ready():
        print(f"{client.user.name} has connected to Discord.")

    # load all cogs
    for folder in os.listdir("modules"):
        if os.path.exists(os.path.join("modules", folder, "cog.py")):
            client.load_extension(f"modules.{folder}.cog")

    client.run(os.getenv("DISCORD_TOKEN"))
コード例 #3
0
def main():
	# allows privledged intents for monitoring members joining, roles editing, and role assignments
	# these need to be enabled in the developer portal as well
	intents = nextcord.Intents.default()
	intents.guilds = True
	intents.members = True

	client = commands.Bot(config.BOT_PREFIX, intents=intents)

	# Get the modules of all cogs whose directory structure is modules/<module_name>/cog.py
	for folder in os.listdir("modules"):
		if os.path.exists(os.path.join("modules", folder, "cog.py")):
			client.load_extension(f"modules.{folder}.cog")

	@client.event
	async def on_ready():
		"""When discord is connected"""
		print(f"{client.user.name} has connected to Discord!")

	# Run Discord bot
	client.run(config.DISCORD_TOKEN)
コード例 #4
0
ファイル: bot.py プロジェクト: hikizisa/Hikineet-Bot
def main():
    try:
        sqliteConnection = sqlite3.connect(DBPATH)
        cursor = sqliteConnection.cursor()

        sqlite_select_Query = "select sqlite_version();"
        cursor.execute(sqlite_select_Query)
        record = cursor.fetchall()

    except sqlite3.Error as error:
        sys.exit(0)

    def get_prefix(bot, message):
        prefixes = ['&']

        # Check to see if we are outside of a guild. e.g DM's etc.
        if not message.guild:
            # Only allow ? to be used in DMs
            return '?'

        # If we are in a guild, we allow for the user to mention us or use any of the prefixes in our list.
        return commands.when_mentioned_or(*prefixes)(bot, message)

    bot = commands.Bot(command_prefix=get_prefix,
                       description='HikiNeet bot for coding practice',
                       case_insensitive=True,
                       guild_subscriptions=True,
                       intents=nextcord.Intents.all())

    base_cog = Base(bot, cursor)
    bot.add_cog(base_cog)
    base_cog.more_cog(Omq(bot, cursor))
    base_cog.more_cog(Basics(bot, cursor, sqliteConnection))
    base_cog.more_cog(Priconne(bot))
    base_cog.more_cog(Osu(bot, cursor))
    base_cog.more_cog(Translate(bot))
    print("Bot is running")
    bot.run(TOKEN)
コード例 #5
0
ファイル: Bot.py プロジェクト: hamzahap/Automata
AUTOMATA_TOKEN = os.getenv("AUTOMATA_TOKEN", None)

if not AUTOMATA_TOKEN:
    logger.error(
        "AUTOMATA_TOKEN environment variable not set, have you created a .env file and populated it yet?"
    )
    exit(1)

intents = nextcord.Intents.default()
intents.members = os.getenv("AUTOMATA_MEMBER_INTENTS_ENABLED",
                            "True") == "True"

bot = commands.Bot(
    "!",
    description=
    "A custom, multi-purpose moderation bot for the MUN Computer Science Society Discord server.",
    intents=intents,
)

bot = commands.Bot(command_prefix="!", help_command=None)


@bot.event
async def on_message(message):
    # Log messages
    if isinstance(message.channel, nextcord.DMChannel):
        name = message.author.name
    else:
        name = message.channel.name
    logger.info(f"[{name}] {message.author.name}: {message.content}")
    await bot.process_commands(message)
コード例 #6
0
ファイル: main.py プロジェクト: c0rexx/pepek-bot
import nextcord
from nextcord.ext import commands

from cogs.garfield_cog import daily_garfield
from lib.emotes import basic_emoji
from lib.config import activities

# Bot's token
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")

intents = nextcord.Intents.default()
intents.members = True
intents.presences = True

bot = commands.Bot(command_prefix="p.", intents=intents)


async def status_changer():
    """Changes bot's activity every so often"""

    while True:
        try:
            await bot.change_presence(activity=random.choice(activities))

        # Connection issue -> wait a little longer
        except nextcord.HTTPException:
            await asyncio.sleep(90)

        await asyncio.sleep(30)
コード例 #7
0
from nextcord.ext import commands
from a import checks
from a.funcs import f
from a.stuff import conf
import a.constants as tt

async def get_prefix(bot, message):
	data = tt.config.find_one({'_id':message.guild.id},{'prefix':1}) if message.guild != None else None
	return commands.when_mentioned_or(config.prefix if not data else data.get('prefix', config.prefix))(bot, message)

intents = nextcord.Intents.default()
intents.members = True

bot = commands.Bot(
	command_prefix = get_prefix,
	case_insensitive = True,
	intents = intents,
	allowed_mentions = nextcord.AllowedMentions(everyone=False,roles=False),
)
ctx = commands.Context
bot.remove_command('help')

print(f"[{f._t()}] starting ...")
for cog in tt.cogs:
	try: 
		bot.load_extension('cogs.'+cog)
		tt.loaded.append(cog)
		print(f"    \033[92m[+] loaded '{cog}'\033[0m")
	except Exception as error:
		print(f"    \033[91m[x] failed to load '{cog}' \033[1m\n{''.join(traceback.format_exception(type(error), error, error.__traceback__))}\033[0m")
if not tt.testing:
	for command in tt.misc.find_one({'_id':'misc'},{'disabled':1}).get('disabled', []):
コード例 #8
0
from datetime import date
from nextcord.ext.commands import command, cooldown
from better_profanity import profanity
from nextcord.ext import commands
from nextcord import Forbidden
from nextcord.utils import get
today = date.today()
load_dotenv()
intents = nextcord.Intents.all()


def get_prefix(bot, message):
    return prefixes.get(str(message.guild.id), DEFAULT_PREFIX)


bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())
intents.members = True
initial_extensions = []

if os.path.exists(os.getcwd() + "/config.json"):

    with open("./config.json") as f:
        configData = json.load(f)

else:
    configTemplate = {"token": "", "Prefix": "!"}

    with open(os.getcwd() + "/config.json", "w+") as f:
        json.dump(configTemplate, f)

token = configData["Token"]
コード例 #9
0
# so we only have to load the word lists into memory one time -> ~0.22MB total
from myconstants import rolesList, activateRoles, load_data

load_data()

# --------------------------------------------------------------------------- #
# Test cases -- uncomment when testing

# from cogs.games import test
# test()

# --------------------------------------------------------------------------- #

intents = nextcord.Intents.all()
nextcord.members = True
client = commands.Bot(command_prefix=',', intents=intents)
client.remove_command('help')


@client.command()
@commands.guild_only()
@commands.has_any_role("Dodo Op")
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')


@client.command()
@commands.guild_only()
@commands.has_any_role("Dodo Op")
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')
コード例 #10
0
import functools
import os
import sys

import nextcord
from loguru import logger

from novelsave.utils.helpers import dotenv_helper
from . import config

logger.configure(**config.logger_config())

try:
    from nextcord.ext import commands
except ImportError as e:
    logger.exception(e)
    sys.exit(1)

bot = commands.Bot("$")

dotenv_helper.load_dotenv()
if os.getenv("MODE", "prod").lower() == "dev":
    bot.slash_command = functools.partial(bot.slash_command,
                                          guild_ids=[int(os.getenv("GUILD"))])

    nextcord.slash_command = functools.partial(
        nextcord.slash_command, guild_ids=[int(os.getenv("GUILD"))])
コード例 #11
0
import nextcord
from nextcord.ext import tasks, commands
import asyncio
import random
import traceback
import sys
import datetime
import mewtwo_config as config

print('Starting Mewtwo.py... This may take some time.')
print('')

intents = nextcord.Intents.all()
bot = commands.Bot(command_prefix='>',
                   intents=intents,
                   owner_id=config.owner,
                   case_insensitive=True)
cogs = ["cogs.general", "cogs.fun", "cogs.nsfw", "cogs.other", "cogs.admin"]

start_time = datetime.datetime.utcnow()

botver = "Mewtwo v2.1"

botstatus = [
    'with >help',
    'Now using Nextcord!',
    'try >help!',
    'try >google!',
    'try >info!',
    'try >avatar!',
    'try >nslookup!',
コード例 #12
0
logging.getLogger("lavalink").setLevel(logging.WARNING)
# set nextcord logging level to WARNING
logging.getLogger("nextcord").setLevel(logging.WARNING)


def load_cogs(bot):
    for f in os.listdir("./trial/Cogs"):
        if f.endswith(".py"):
            bot.load_extension(f"trial.Cogs.{f[:-3]}")


intents = Intents.default()
intents.members = True

bot = commands.Bot(
    command_prefix=Config.PREFIX,
    intents=intents,
)

bot._enable_debug_events = True
# testing mode is enabled by passing "test" as command line argument
bot.testing = len(sys.argv) > 1 and sys.argv[1] == "debug"

bot_activity = Activity(
    type=ActivityType.listening,
    name=f"{f'{Config.PREFIX}help' if not bot.testing else 'debug'}",
)


@bot.event
async def on_ready():
    with open("logs/guildss.txt", "w") as f:
コード例 #13
0
ファイル: bot.py プロジェクト: wanony/PublicBot

def get_prefix(disclient, message):
    guild = message.guild
    if guild:
        prefix = get_prefix_db(guild.id)
        if prefix:
            return commands.when_mentioned_or(*prefix)(disclient, message)
        else:
            return commands.when_mentioned_or(*default_prefix)(disclient,
                                                               message)
    else:
        return commands.when_mentioned_or(*default_prefix)(disclient, message)


disclient = commands.Bot(intents=intents,
                         command_prefix=get_prefix)  # , intents=intents)
disclient.remove_command('help')
# commands.DefaultHelpCommand(width=100, dm_help=True, dm_help_threshold=100)


@disclient.event
async def on_ready():
    await disclient.change_presence(activity=discord.Activity(
        type=discord.ActivityType.watching, name=f"for {default_prefix}help"),
                                    status=discord.Status.online)
    print(
        f"bot is online as {disclient.user.name} in {len(disclient.guilds)} guilds!:"
    )
    for guild in disclient.guilds:
        # add if guild id not in guild table here...
        added = add_guild_db(guild.id)
コード例 #14
0
import nextcord
from nextcord.ext import commands

token = open('Party Wizard/code.txt', 'r')

intents = nextcord.Intents.default()
intents.members = True

tokenstr = token.read()

if tokenstr[0] != "O":
    bot = commands.Bot(command_prefix=['wizard ', 'wiz ', 'Wizard ', 'Wiz '], intents=intents)
else:
    bot = commands.Bot(command_prefix=['test ', 't ', 'T ', 'Astolfo ', 'astolfo ', 'Test '], intents=intents)

initial_extensions = ['cogs.DnD',
                      'cogs.Karma',
                      'cogs.Games', 
                      'cogs.Scheduling', 
                      'cogs.TextBased', 
                      'cogs.Utility',
                      'cogs.BitD']

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)
        print(f"{extension} added")

@bot.slash_command(name="short_help", description="Shorter help page.", guild_ids=[706471625544957972])
async def shortHelp(ctx):
    cogs =  []
コード例 #15
0
ファイル: bot.py プロジェクト: vzdc/ZDC.Discord
import os

from dotenv import load_dotenv
from nextcord import Intents
from nextcord.ext import commands

load_dotenv()

discord_token: str | None = os.getenv("DISCORD_TOKEN")

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

cogs: list[str] = [
    os.path.join(path, file)[2:-3].replace("/", ".").replace("\\", ".")
    for path, _, files in os.walk('./cogs')
    for file in files
    if file.endswith('.py')
]

for cog in cogs:
    try:
        print(f"Loading cog {cog}")
        bot.load_extension(cog)
        print(f"Loaded cog {cog}")
    except Exception as e:
        print(f"Failed to load cog {cog}\n{type(e).__name__}: {e}")


bot.run(discord_token)