def __init__(self): intents = discord.Intents.all() commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or("Leo "), case_insensitive=True, help_command=PrettyHelp(color=discord.Color.purple, show_index=False), intents=intents) # Add Cogs Here self.add_cog(basic.Basic()) self.add_cog(data_access.DataAccess())
def __init__(self): self.ready = False self.cogs_ready = Ready() self.scheduler = AsyncIOScheduler() db.autosave(self.scheduler) super().__init__(command_prefix=get_prefix, owner_ids=OWNER_IDS, help_command=PrettyHelp(color=discord.Color.green()), intents=Intents.all() )
def __init__(self, **kwargs): self.stats = {} self.theme_color = kwargs.pop("theme_color") self.dark_theme_color = kwargs.pop("dark_theme_color") self.error_color = kwargs.pop("error_color") self.db: Database = kwargs.pop("db") self.cache: Cache = kwargs.pop("cache") self.pipe = kwargs.pop("pipe") self.cluster_name = kwargs.pop("cluster_name") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) super().__init__( help_command=PrettyHelp(color=self.theme_color), command_prefix=self._prefix_callable, **kwargs, loop=loop, ) self.websocket = None self._last_result = None self.ws_task = None self.responses = asyncio.Queue() self.eval_wait = False log = logging.getLogger(f"Cluster#{self.cluster_name}") log.setLevel(logging.DEBUG) log.handlers = [ logging.FileHandler( f"logs/cluster-{self.cluster_name}.log", encoding="utf-8", mode="a", ) ] log.info(f'[Cluster#{self.cluster_name}] {kwargs["shard_ids"]}, ' f'{kwargs["shard_count"]}') self.log = log self.loop.create_task(self.ensure_ipc()) self.loop.run_until_complete(self.db.init_database()) for ext in kwargs.pop("initial_extensions"): self.load_extension(ext) self.add_check(checks.not_disabled) try: self.run(kwargs["token"]) except Exception as e: raise e from e else: sys.exit(-1)
def __init__(self, **kwargs): """Initialize Bot.""" super().__init__( command_prefix=commands.when_mentioned_or(*kwargs.pop("prefix")), description=kwargs.pop("description"), intents=discord.Intents.all(), case_insensitive=kwargs.pop("case_insensitive"), help_command=PrettyHelp(show_index=False, color=discord.Color.purple()), ) self.app_info = None self.loop.create_task(self.load_all_extensions())
def __init__(self): urllib3.disable_warnings() intents = discord.Intents.default() intents.members = True super().__init__( command_prefix=self.determine_prefix, description= "Your favorite Alter Ego, now as a bot. [under development]", help_command=PrettyHelp(), intents=intents, case_insensitive=True) if 'reminders' not in db: db['reminders'] = {} self.prefix_db = SqliteDict('./prefix.sqlite', autocommit=True)
def main(): # задаём префикс, команду "help" и цвет для embedded bot = commands.Bot(command_prefix=".", help_command=PrettyHelp(active_time=120, color=0xA0CFE5)) load_ext(bot) # events @bot.event async def on_ready(): await bot.change_presence(status=discord.Status.online, activity=discord.Game(".help")) print("Online!") # bot run bot.run(token)
def __init__(self): super().__init__(command_prefix=prefix, case_insensitive=True, guild_subscriptions=True, fetch_offline_members=True, intents=Intents.all(), help_command=PrettyHelp( nav=Navigation(":discord:743511195197374563", "👎", "\U0001F44D"), color=discord.Color.dark_gold())) self.client_id = 0 self.Version = 3.0 self.log = Log() self.scheduler = AsyncIOScheduler() self.helper = helper self.cache = self.helper.DbCache(self.loop) self.sql = Db() self.booted = False
def __init__(self): # Initialises the actual commands.Bot class intents = discord.Intents.all() intents.members = True super().__init__(command_prefix=self.determine_prefix, description=config.description, loop=asyncio.get_event_loop(), intents=intents, case_insensitive=True, help_command=PrettyHelp(color=discord.Colour.blue())) self.guild = None self.error_channel = None self.data = DataHelper() self.database_handler = None self.latest_joins = {} self.restart_event: Union[asyncio.Event, None] = None self.mongo: Union[MongoDB, None] = None self.restart_waiter_lock = asyncio.Lock() self.restart_waiters = 0
def __init__(self): intents = discord.Intents.all() commands.Bot.__init__(self, command_prefix=commands.when_mentioned_or("Bjørn "), case_insensitive=True, help_command=PrettyHelp(color=Color.purple(), show_index=False), intents=intents) # Set up Firebase Database # Currently disabled as not needed due to disabled birthday feature # config = { # 'apiKey': os.getenv('FIREBASE_API_KEY'), # 'authDomain': os.getenv('FIREBASE_AUTH_DOMAIN'), # 'storageBucket': os.getenv('FIREBASE_STORAGE_BUCKET'), # 'databaseURL': os.getenv('FIREBASE_DATABASE_URL') # } # firebase = pyrebase.initialize_app(config) # database = firebase.database() # Add cogs here self.add_cog(basic_cog.Basic(self)) self.add_cog(translate_cog.Translate()) self.add_cog(catch_cog.Catch()) self.add_cog(famous_vikings_cog.FamousVikings()) self.add_cog(meme_cog.Meme(self)) self.add_cog(awards_cog.Awards(self))
return commands.when_mentioned_or(*prefixes)(client, message) # thanks evieepy for this snippet of code. intents = discord.Intents.default() intents.members = True # F**k intents. intents.guilds = True bot = commands.Bot( # Create a new bot command_prefix=get_prefix, # Set the prefix description=get_config_parameter('bot_description', str), # Set a description for the bot owner_id=get_config_parameter('owner_id', int), # Your unique User ID case_insensitive=True, # Make the commands case insensitive intents=intents, # I think I made intents help_command=PrettyHelp() # Sets custom help command to discord_pretty_help's ) @bot.event async def on_ready(): if verbose: print('Bot is ready: everything should have loaded successfully.') else: if os.name == 'nt': if clear_terminal: os.system("cls") if change_terminal_name: os.system(f"title {bot.user}") elif os.name == 'posix': if clear_terminal:
import discord from discord.ext import commands, tasks import os import youtube_dl from pretty_help import PrettyHelp token = os.environ["TOKEN"] client = commands.Bot(command_prefix="j!", help_command=PrettyHelp()) @client.event async def on_ready(): await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="JoJo || j!help")) # Import cog for filename in os.listdir("./cogs"): if filename.endswith(".py"): client.load_extension(f"cogs.{filename[:-3]}") print(f"{filename} has loaded.") client.run(token)
# Get Members intent intents = discord.Intents.all() # Configure help menu menu = DefaultMenu(page_left="⬅️", page_right="➡️") # Configure the bot BOT_TOKEN = os.getenv("BOT_TOKEN") bot = commands.Bot( command_prefix=["luci ", "Luci "], case_insensitive=True, strip_after_prefix=False, intents=intents, self_bot=False, owner_id=707557256220115035, help_command=PrettyHelp(color=0xf34949, sort_commands=True), description="A General-Purpose Discord Bot Created by luciferchase#6310") # Set up logging logging.basicConfig(level=logging.WARNING) # Register Cogs bot.add_cog(aki.Aki(bot)) bot.add_cog(bigmoji.Bigmoji(bot)) bot.add_cog(birthday.Birthday()) bot.add_cog(botstatus.Botstatus(bot)) bot.add_cog(comics.Comics(bot)) bot.add_cog(connect4.Connect4(bot)) bot.add_cog(conversationgames.ConversationGames()) bot.add_cog(core.Core(bot)) bot.add_cog(covid.Covid(bot))
import random import discord from discord.ext import commands from pretty_help import PrettyHelp 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") bot = commands.Bot(command_prefix="p.") bot.help_command = PrettyHelp(color=discord.Color.dark_red()) 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 discord.HTTPException: await asyncio.sleep(90) await asyncio.sleep(30)
import discord import os from discord.ext import commands, tasks from itertools import cycle from pretty_help import PrettyHelp, Navigation bot = commands.Bot(command_prefix = '21/', case_insensitive = True) status = cycle(['Waiting for 21/help', 'Hi', '9+10=21', '''hi hi''', "21"]) nav = Navigation(":arrow_up:") color = discord.Color.dark_green() bot.help_command = PrettyHelp(navigation=nav, color=color, active_time=10) @bot.event async def on_ready(): change_status.start() print('We have logged in as {0.user}'.format(bot)) # Background Tasks @tasks.loop(seconds = 10) async def change_status(): await bot.change_presence(status = discord.Status.online, activity = discord.Game(next(status))) # Events
with open('./data/prefixes.json', 'r') as f: prefixes = json.load(f) if not message.guild: return ("dm! ") try: return prefixes[str(message.guild.id)] except KeyError: with open('./data/prefixes.json', 'w') as f: print("Criando Novo Prefixo....") prefixes[str(message.guild.id)] = config('PREFIX') json.dump(prefixes, f, indent=4) return prefixes[str(message.guild.id)] bot = commands.Bot(command_prefix=get_prefix, help_command=PrettyHelp(), description="Um Simples bot do discord!") cmds: list = [] cmd_folders = [] for r, s, files in os.walk("./Commands"): for folders in s: cmd_folders.append(folders) for folder in cmd_folders: for file in os.listdir(f"./Commands/{folder}"): if file.endswith(".py"): command = file.replace('.py', "") cmds.append(command) for cmd in cmds: try: try:
# List cogs to be loaded initial_extensions = ["memes", "music"] # Create instance of Discord bot class bot = commands.Bot(command_prefix=determine_prefix, description='The Bestest of Bois!') # Initiate local bot class variables bot.memes_shown = 0 bot.recent_meme = "" bot.recent_location = "" # Create better looking help command using PrettyHelp bot.help_command = PrettyHelp(color=discord.Color.dark_gold(), show_index=False, no_category="Commands", sort_commands=True) # Load our extensions(cogs) listed above if __name__ == '__main__': for extension in initial_extensions: bot.load_extension(extension) # Create message that is sent to default server channel upon joining @bot.event async def on_guild_join(guild): if guild.system_channel: await guild.system_channel.send( "WOW! Thanks for the invite. \nMy default prefix is '" + str(default_prefix) + "'. Type " + str(default_prefix) +
import discord from discord.ext import commands from pretty_help import PrettyHelp bot = commands.Bot(command_prefix=".", description='A bot specially made for fun', owner_id=762628291508043786, case_insensitive=True) bot.load_extension('cog_admin') bot.load_extension('cog_info') bot.load_extension('cog_calculator') bot.load_extension('cog_stuff') bot.help_command = PrettyHelp() bot.help_command = PrettyHelp(index_title="CatsyBot Help Page", no_category="Other Stuff") @bot.event async def on_ready(): await bot.change_presence(activity=discord.Game( name=".help | on " + str(len(bot.guilds)) + " Servers.", type=0)) print('Darth Cats is online') print( '██████╗░░█████╗░████████╗ ██╗░██████╗ ██████╗░███████╗░█████╗░██████╗░██╗░░░██╗' ) print( '██╔══██╗██╔══██╗╚══██╔══╝ ██║██╔════╝ ██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗░██╔╝' ) print( '██████╦╝██║░░██║░░░██║░░░ ██║╚█████╗░ ██████╔╝█████╗░░███████║██║░░██║░╚████╔╝░' )
import os import discord from discord.ext import commands import datetime from pretty_help import PrettyHelp client = commands.Bot(command_prefix="--", help_command=PrettyHelp(no_category="Base commands", sort_command=True, color=discord.Color.orange())) @client.command(help="Yeets the bot out of existance.") async def yeet(ctx): await client.close() print(f"Bot have been yeeted out of existance by {ctx.author.name}") @client.listen("on_ready") async def ready(): print("Bot successfully deployed.") @client.listen("on_disconnect") async def dc(): print("Bot has been disconnected.") @client.group(case_insensitive=True) async def ext(ctx): if ctx.invoked_subcommand is None or ctx.command_failed:
async def after_invoke(self, ctx: Context): """Deletes the message if invoked with a silent prefix""" if ctx.prefix == config['bot']['silent_prefix']: try: await ctx.message.delete() except discord.Forbidden: pass prefixes = (config['bot']['prefix'], config['bot']['silent_prefix']) bot = CBot( commands.when_mentioned_or(*sorted(prefixes, key=len, reverse=True)), case_insensitive=True, strip_after_prefix=True, help_command=PrettyHelp(color=0x42F56C, ending_note="Prefix: >>", show_index=False), intents=discord.Intents.all()) for file in os.listdir('./cogs'): if file[0] == '_': continue extension = os.path.splitext(file)[0] try: bot.load_extension(f"cogs.{extension}") print(f"Loaded extension '{extension}'") except Exception as e: exception = traceback.format_exc() logger.error(f"Failed to load extension {extension}\n{exception}")
if message.author.id == config.blacklist: return "blacklist" await bot.process_commands(message) # custom ending note using the command context and help command formatters ending_note = "The ending not from {ctx.bot.user.name}\nFor command {help.clean_prefix}{help.invoked_with}" # ":discord:743511195197374563" is a custom discord emoji format. Adjust to match your own custom emoji. nav = Navigation("◀️", "▶️") color = utils.random_color() bot.help_command = PrettyHelp(navigation=nav, color=color, active_time=30, ending_note=ending_note, index_title="help", no_category="no category cmd") @bot.command() async def edit(ctx): msg = await ctx.send("[") for i in range(1, 11): await asyncio.sleep(1) await msg.edit(content="[" + ">" * i) @bot.command() async def version(ctx): await ctx.send(config.version)
from internal.constants import ACC_PURPLE logger = logging.getLogger() logger.setLevel(logging.INFO) consoleHandle = logging.StreamHandler() consoleHandle.setLevel(logging.INFO) consoleHandle.setFormatter( logging.Formatter("%(name)-18s :: %(levelname)-8s :: %(message)s")) logger.addHandler(consoleHandle) bot = commands.Bot( command_prefix=commands.when_mentioned_or(";"), description="A bot for CS/IT @ ACC Discord server.", intents=discord.Intents.all(), help_command=PrettyHelp(show_index=False, color=ACC_PURPLE), case_insensitive=True, ) async def load_all_extensions(): """Load all *.py files in /cogs/ as Cogs.""" cogs = [x.stem for x in Path("cogs").glob("*.py")] logger.info("") logger.info("Loading extensions...") for extension in cogs: try: bot.load_extension(f"cogs.{extension}") logger.info(f"loaded {extension}") except Exception as e: error = f"{extension} - {type(e).__name__} : {e}"
embed2.add_field(name="서버 닉네임", value=f"{msg.author.display_name}", inline=False) embed2.add_field(name="현재 상태", value=f"{user_status}({msg.author.status})", inline=False) embed2.add_field(name="봇 여부", value=f"{msg.author.bot}", inline=False) embed2.add_field(name="디스코드 시스템 메시지 여부", value=f"{msg.author.system}", inline=False) embed2.add_field(name="역할들", value="".join([role.mention for role in msg.author.roles]), inline=False) embed2.add_field(name="하는중...", value=f"{msg.author.activity}", inline=False) await msg.send(embeds=[embed2]) except: await msg.send(content="오류가 발생했습니다.\n혹시 DM 채널에서 사용하고계신가요? 서버에서 사용 부탁드려요 :)") pass @slash.slash(name="봇정보") async def scbotinfo(ctx): await ctx.send(content=f"서버 수: {len(bot.guilds)}\n유저 수: {len(bot.users)}\n파이썬 버전: {sys.version}", complete_hidden=True) @slash.slash(name="인공지능대화", options=[manage_commands.create_option("string", "띵이봇에게 할말!", 3, True)]) async def scchat(ctx, string): data = await Ping.Pong(ctx.author.id, string, NoTopic=False) embed = discord.Embed( title="띵이봇과 대화하기!", description=data['text'], color=RandomColor() ) embed.set_footer(text="띵이봇 인공지능") if data['image'] is not None: embed.set_image(url=data['image']) await ctx.send(embeds=[embed]) bot.help_command = PrettyHelp(color=RandomColor(), active_time=300, no_category="다음 페이지로 넘겨주세요!", index_title="띵이봇 도움말!") bot.run(os.environ['token'])
with open(configFile, 'w') as outfile: json.dump(data, outfile) with open(configFile, "r") as config: data = json.load(config) token = data["token"] prefix = data["prefix"] server = data["server"] # Intents intents = discord.Intents().all() bot = commands.Bot(command_prefix=prefix, intents=intents) # Setting up Help Command Stuff colorHelp = discord.Color.dark_blue() bot.help_command = PrettyHelp(color=colorHelp) initial_extensions = ["Cogs.onCommandError", "Cogs.commands"] print(initial_extensions) if __name__ == '__main__': for extension in initial_extensions: try: bot.load_extension(extension) except Exception as e: print(f"Failed to load extension {extension}") # #RUNNING# #
def run(self, *args, **kwargs): load_dotenv() self.help_command = PrettyHelp(color=discord.Colour.green()) for extension in self.extensions: self.load_extension(extension) super().run(os.getenv("BOT-TOKEN"))
"bot":{ "no_ext_abort" : true, "command_prefix":"!", "ext_dir":"extensions", "owner_ids":[1] } } To add keys / to extensions (or the bot) put them in "core/keys.json" An example of this can be found in "example keys.json" ''' bot = commands.Bot(command_prefix=commands.when_mentioned_or( config["bot"]["command_prefix"]), owner_ids=set(config["bot"]["owner_ids"]), help_command=PrettyHelp()) #initializes the bot print("Loading Core cogs...") file = importlib.import_module("core.core-extensions") for i in file.cogs: bot.add_cog(i(bot, config["bot"])) print("Checking " + config["bot"]["ext_dir"] + "/ for extensions...") for i in os.listdir(config["bot"]["ext_dir"]): #searches the extension dir if i.endswith(".py"): print("Searching {} for cogs...".format(i)) try: file = importlib.import_module( config["bot"]["ext_dir"] + "." +
log_stream = logging.StreamHandler() log_stream.setFormatter(formatter) log_stream.setLevel(logging.INFO) logger.addHandler(file_handler) logger.addHandler(log_stream) logger.info("Logger Active") intents = discord.Intents.all() bot = commands.Bot(command_prefix=COMMAND_PREFIX(), case_insensitive=True, intents=intents) bot.help_command = PrettyHelp(show_index=True, sort_commands=True, no_category=True, color=0x00f2ff) for filename in os.listdir("./cogs"): if filename.endswith(".py") and \ filename != "main.py": bot.load_extension(f"cogs.{filename[:-3]}") logger.info(f"Loaded: cogs.{filename[:-3]}") # noinspection PyBroadException,SqlNoDataSourceInspection,SqlResolve @bot.after_invoke async def reply_with_read(ctx: Context): try: failed = await ctx.guild.fetch_emoji(emoji_id=EmojiIds.Failed) success = await ctx.guild.fetch_emoji(emoji_id=EmojiIds.Success)
from owner_cog import Owner from util_cog import Utility from lb_cog import Leaderboard from pretty_help import PrettyHelp import functions import converters from secrets import TOKEN, BETA_TOKEN, OWNER_ID, INVITE, SUPPORT_SERVER, SUPPORT_ID, SUGGESTION_CHANNEL PREFIXES = functions.get_prefix BETA_PREFIXES = functions.get_prefix DOWNVOTE = '⬇️' UPVOTE = '⬆️' if len(sys.argv) == 0: bot = Bot(command_prefix=PREFIXES, help_command=PrettyHelp(color=0xFCFF00)) else: if sys.argv[1].lower() == 'beta': bot = Bot(command_prefix=BETA_PREFIXES, help_command=PrettyHelp(color=0xFCFF00)) else: print("Invalid Argument. Did you mean \"beta\"?") exit() running = True async def loop_save(): while dbh.database is None: await sleep(5) while running: await sleep(60)
import pandas as pd #import neccesary discord libs import discord from discord.ext import commands #used to get proper dates for certain time sensitive commands week_ago = date.today() - timedelta(7) current_date = date.today() + timedelta(1) #initialization of the environment to run the bot #load_dotenv() #f = open("/root/token", "r") f = open("../secret", "r") TOKEN = f.readline() bot = commands.Bot(command_prefix="$", help_command=PrettyHelp()) #client = discord.Client() @bot.event async def on_ready( ): #this finction will run when the bot has succesfully connected print(f'{bot.user.name} has connected to Discord!') @bot.event async def on_message(ctx): # we do not want the bot to reply to itself if ctx.author == bot.user: return
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)
from pretty_help import Navigation, PrettyHelp, __version__ def test_version(): assert __version__ == "1.1.0" # replace with your token TOKEN = "TOKEN" # ":discord:743511195197374563" is a custom discord emoji format. Adjust to match your own custom emoji. nav = Navigation(":discord:743511195197374563", "👎", "\U0001F44D") bot = commands.Bot(command_prefix="!", description="this is the bots descripton") bot.help_command = PrettyHelp(navigation=nav) @bot.event async def on_ready(): print(f"Logged in as: {bot.user.name}") print(f"With ID: {bot.user.id}") class TestCog(commands.Cog): """This is a cog for testing purposes""" @commands.command() async def testcommand(self, ctx: commands.Context): await ctx.send("This is a test command")