示例#1
0
def get_prefix(bot, msg):
    """A callable Prefix for our bot. This could be edited to allow per server prefixes."""

    # Notice how you can use spaces in prefixes. Try to keep them simple though.
    prefixes = ['.']

    return commands.when_mentioned_or(*prefixes)(bot, msg)
示例#2
0
    def __init__(self, prefix='!crab'):
        # Could just use command_prefix arg, but this allows for a default prefix
        super().__init__(command_prefix=commands.when_mentioned_or(prefix),
                         description="Huh, another bot")
        # loop.set_debug(True)  # Set asyncio loop to output more info for debugging
        # self.add_listener(self.on_ready)  # TIL on_ready in a Bot subclass is already registered

        self.cogs_update_lists = {}
示例#3
0
    def __init__(self, command_prefix=commands.when_mentioned_or("#!"),
            formatter=None,
            name="BasicBot",
            description="""Tnybot is a basic bot that includes custom commands and notifications""",
            pm_help=False, **options):
        self.unit_tests = options.pop('unit_tests', False)
        super().__init__(command_prefix, formatter, description, pm_help, **options)

        self.name = name
        if not self.unit_tests and not sys.platform.startswith('win'):  # pragma: no cover
            # This is needed for safe shutdown on Heroku.
            self.loop.add_signal_handler(getattr(signal, "SIGTERM"), self.exit)
示例#4
0
文件: main.py 项目: GetRektByMe/Pixie
    def __init__(self, *args, **kwargs):
        super().__init__(command_prefix=when_mentioned_or(setup_file["discord"]["command_prefix"]),
                         description="A bot for weebs programmed by Recchan")

        # Set a custom user agent for Pixie
        self.http.user_agent = user_agent

        # Logging setup
        redirect_logging()
        StreamHandler(sys.stderr).push_application()
        self.logger = Logger("Pixie")
        self.logger.level = getattr(logbook, setup_file.get("log_level", "INFO"), logbook.INFO)
        logging.root.setLevel(self.logger.level)
示例#5
0
文件: bot.py 项目: Maverun/Nurevam
async def command_checker(msg):
    try:
        if isinstance(msg.channel,discord.DMChannel):
            if "!reply" in msg.content:
                bot.command_prefix = commands.when_mentioned_or("!")
                return

        if bot.user.id == 181503794532581376:
            bot.command_prefix = commands.when_mentioned_or("$")
            bot.pm_help = False
            return

        cmd_prefix = await bot.db.redis.get("{}:Config:CMD_Prefix".format(msg.guild.id)) or "!"
        cmd_prefix = cmd_prefix.split(",")
        if '' in cmd_prefix: #check if "none-space" as a command, if true, return, in order to prevent any spam in case, lower chance of getting kick heh.
            return
        bot.command_prefix = commands.when_mentioned_or(*cmd_prefix)
        if "help" in msg.content: #changing setting for help, if guild owner want Help command to be via PM or to guild.
            if await bot.db.redis.get("{}:Config:Whisper".format(msg.guild.id)) == "on":
                bot.pm_help =True
            else:
                bot.pm_help=False
    except:
        pass
示例#6
0
    def __init__(self, conf_path=paths.BOT_CONFIG, debug_instance=False):
        self.app_info = None
        self.owner = None
        self.do_restart = False
        self.start_time = time.time()
        self.conf = config.Config(conf_path, encoding='utf-8')
        self.debug_instance = debug_instance

        # Init the framework and load extensions
        super().__init__(description=self.conf.description,
                         command_prefix=commands.when_mentioned_or('€'),
                         help_attrs={'hidden': True})
        self.load_extensions(paths.COGS)

        # Accept restarts after everything has been initialised without issue
        self.do_restart = True
示例#7
0
	def __init__(self, *args, **kwargs):
		self.loop = kwargs.pop('loop', asyncio.get_event_loop())
		asyncio.get_child_watcher().attach_loop(self.loop)
		self.dev_mode = kwargs.pop('dev_mode', False)
		self.token = os.getenv('bot_token') if not self.dev_mode else os.getenv('bot_beta_token')
		self.self_bot = kwargs.pop('self_bot', False)
		if self.self_bot:
			self.token = os.getenv('notsosuper_token')
		shard_id = kwargs.get('shard_id', 0)
		command_prefix = kwargs.pop('command_prefix', commands.when_mentioned_or('.'))
		init_logging(shard_id, self)
		super().__init__(command_prefix=command_prefix, *args, **kwargs)
		self.remove_command('help')
		init_funcs(self)
		self.owner = None
		self.start_time = time.time()
		self.own_task = None
		self.last_message = None
		self.command_messages = {}
示例#8
0
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'),
                         intents=intents)
示例#9
0
import os

import discord
from discord.ext import commands

import config
from cogs.utils import checks

# description showed when you use the help command
description = 'test'

# sets up the bots characteristics.
# command_prefix is the character used before commands
help_attrs = dict(hidden=True)
bot = commands.Bot(command_prefix=commands.when_mentioned_or(config.prefix),
                   description=description,
                   pm_help=None,
                   help_attrs=help_attrs)


# a quick thing i made to look in a cogs folder and save all extensions in
# the list


def list_cogs():
    return ['cogs.' + i.replace('/', '\\').split('\\')[0][:-3]
            for i in os.listdir('cogs') if i.endswith('.py')]


def load_cog(cog):
    try:
示例#10
0
import random, datetime
import urllib.request
import myhelp
# change this line to import your own token.
from tokens import get_token
from cogs.func import lists
from cogs.func.helper import *

# ===== COG IMPORTS ===== #
from cogs import music, useful, fun

# ===== BASIC LOADS ===== #

description = '''AnojiBot v0.5.2a'''
formatter = myhelp.CustomHelp(show_check_failure=False)
bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description, pm_help=False, formatter=formatter)


if not discord.opus.is_loaded():
    # the 'opus' library here is opus.dll on windows
    # or libopus.so on linux in the current directory
    # you should replace this with the location the
    # opus library is located in and with the proper filename.
    # note that on windows this DLL is automatically provided for you
    discord.opus.load_opus('opus')

# ===== GENERAL HELPER COMMANDS ===== #

async def send_cmd_help(ctx):
    if ctx.invoked_subcommand:
        pages = bot.formatter.format_help_for(ctx, ctx.invoked_subcommand)
示例#11
0
    @play.before_invoke
    @yt.before_invoke
    @stream.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError(
                    "Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()


bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"),
    description="Relatively simple music bot example",
)


@bot.event
async def on_ready():
    print("Logged in as {0} ({0.id})".format(bot.user))
    print("------")


bot.add_cog(Music(bot))
bot.run("token")
示例#12
0
    @commands.command()
    async def stop(self, ctx):
        """Stops and disconnects the bot from voice"""

        await ctx.voice_client.disconnect()

    @play.before_invoke
    @yt.before_invoke
    @stream.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError("Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"),
                   description='Relatively simple music bot example')

@bot.event
async def on_ready():
    print('Logged in as {0} ({0.id})'.format(bot.user))
    print('------')

bot.add_cog(Music(bot))
bot.run('token')
示例#13
0
文件: bot.py 项目: b00000001/main_bot
import discord
import os

from discord.ext import commands
from cogs.utils import checks

#description showed when you use the help command
description = "test"

#sets up the bots characteristics. 
#command_prefix is the character used before commands
help_attrs = dict(hidden=True)
bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description, pm_help=None, help_attrs=help_attrs)
                   
#a quick thing i made to look in a cogs folder and save all extensions in the list
def list_cogs():
    return ["cogs." + i.replace("/", "\\").split("\\")[0].replace(".py", "")
        for i in os.listdir("cogs") if i.endswith(".py")]

def load_cog(cog):
    try:
        bot.load_extension(cog)
        print('Loaded {}'.format(cog))
    except Exception as e:
        print('Failed to load cog {}\n{}: {}'.format(
            cog, type(e).__name__, e))

@bot.command(name="exit")
async def exit():
    await bot.logout()
 
示例#14
0
def get_prefix(bot, msg):
    """A callable Prefix for our bot. This could be edited to allow per server prefixes."""

    prefixes = ['s.']  #Your bot prefix(s)

    return commands.when_mentioned_or(*prefixes)(bot, msg)
        'frog.tips.local.ini',
        'frog.tips.ini']:
    if os.path.isfile(inifile):
        config.read(inifile)
        break  # First config file wins
MAIN = config['MAIN']


def get_cache_dir(app_name='frogsay'):
    return os.path.join(click.get_app_dir(app_name), 'croak_cache')


description = '''PLEASE READ THE FROG MANUAL AS OUR DOCUMENTATION WRITER HAS PUT HUNDREDS OF HOURS OF WORK INTO IT.
TO INFEST SERVER WITH FROG TIPS: https://discordapp.com/oauth2/authorize?&client_id=203243007317639168&scope=bot&permissions=3072'''
bot = commands.Bot(
    command_prefix=commands.when_mentioned_or('!'),
    description=description)


@bot.event
@asyncio.coroutine
def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


@bot.group(pass_context=True)
@asyncio.coroutine
def tip(ctx):
示例#16
0
def get_guild_prefix(bot, message):
    prefix = db.field("SELECT prefix FROM guilds WHERE guild_id = ?;", message.guild.id)
    return when_mentioned_or(prefix)(bot, message)
示例#17
0
def get_prefix(bot, message):
    prefixes = ['t/']
    return commands.when_mentioned_or(*prefixes)(bot, message)
示例#18
0
def get_prefix(client, message):
    prefixes = ['$steak ', '$s ']
    return commands.when_mentioned_or(*prefixes)(client, message)
示例#19
0
文件: bot.py 项目: oicu8/deerhunt
async def get_prefix(bot, message):
    extras = [
        await bot.db.get_pref(message.channel, "prefix"), "deerhunt", "dh!",
        "dh", "Dh", "Dh!", "dH!", "dH", "DH!", "DH"
    ]
    return commands.when_mentioned_or(*extras)(bot, message)
示例#20
0
import discord
import asyncio
import aiofiles


from discord.ext import commands

intents = discord.Intents.all()
client = commands.Bot(command_prefix=commands.when_mentioned_or('!'),intents=intents)
client.ticket_configs = {}

@client.command()
async def ping(ctx):
    embed=discord.Embed(title="Bot Ping",description=f"My ping is {round(client.latency * 1000)}ms ",color=discord.Colour.gold())
    await ctx.reply(embed=embed)

@client.event
async def on_ready():
    print("Bot is online")


@client.event
async def on_raw_reaction_add(payload): #When a reaction is added
    if payload.member.id != client.user.id and str(payload.emoji) == u"\U0001F3AB": #Checks if the reaction is not made by a bot an emoji is "🎫"
        msg_id, channel_id, category_id = client.ticket_configs[payload.guild_id] 

        if payload.message_id == msg_id: #checks if the reaction message is equal to the message id in ticket_configs.txt
            guild = client.get_guild(payload.guild_id)

            for category in guild.categories:
                if category.id == category_id:
示例#21
0
文件: main.py 项目: Freakus/Theriah



class AmbiguousMemberException(Exception):
    pass


class MissingAuth(Exception):
    pass



description = '''A friendly magical otter from the village of Boskrill.
There are a number of things he can do for you:'''
bot = commands.Bot(command_prefix=commands.when_mentioned_or('?'), description=description, pm_help=True)
bot.load_extension('tags')
bot.load_extension('mchelper')

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    print(discord.utils.oauth_url(CLIENT_ID, permissions=None))
    print('------')
    for s in bot.servers:
        print(s.name)
        print(', '.join([str(channel) for channel in s.channels]))
    print('------')
示例#22
0
 def __init__(self):
     super().__init__(command_prefix=commands.when_mentioned_or(">"),
                      owner_id=276707898091110400,
                      case_insensitive=True)
示例#23
0
文件: bot.py 项目: ewong18/Roc-Bot
def get_prefix(bot, message):
    """A callable Prefix for our bot. This could be edited to allow per server prefixes."""
    prefixes = ['!']
    # 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)
示例#24
0
 def __init__(self):
     super().__init__(command_prefix=commands.when_mentioned_or('$'))
示例#25
0
import discord
import codecs
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import string
import random

startup_extensions = ['gifs', 'executer', 'emoji', 'bdcommands', 'games', 'query', 'fun','reminder']
owner = [343395225571426304, 402829897514352641]  
bot = commands.Bot(command_prefix=commands.when_mentioned_or('-', 'asuna ', 'Asuna ', 'Asuna, ', 'asuna, '))
client = discord.Client()


class Main_Commands():
    def __init__(self, bot):
        self.bot = bot

if __name__ == '__main__':
    for extension in startup_extensions: 
        try:
            bot.load_extension("cogs.{}".format(extension))
        except Exception as e:
            exe = '{}: {}'.format(type(e).__name__, e)  
            print('Failed to load extension {}\n{}'.format(extension, exe))

# async def purge_role(ctx, member, role):
#     try:
#         if role.name.lower() in ["lucky star","insane","chatterbox","water wave","unicorn","sparkling stars","cupcake","marshmallow","hello kitty","sparklers"]:
#             await member.remove_roles(role, reason='Cleaning up')
#             await ctx.send(f'\N{WHITE HEAVY CHECK MARK} Successfully removed {role} from {member}')
示例#26
0
import os
import logging
import discord
import datetime
import asyncio

from discord.ext import commands
from discord import Webhook, RequestsWebhookAdapter

logging.basicConfig(level=logging.ERROR)

bot = commands.Bot(commands.when_mentioned_or('ws'), case_insensitive=True,
                   strip_after_prefix=True, help_command=None, max_messages=2000,
                   activity=discord.Game(name="ws help"))

@bot.event
async def on_ready():
    print('{0.user} connected!'.format(bot))
    embed = discord.Embed(color=0x2ecc71, description='🌱',
                          timestamp=datetime.datetime.utcnow())
    await bot.get_channel(int(os.getenv('LOG_CHANNEL'))).send(embed=embed)


@bot.event
async def on_error(event, *args, **kwargs):
    embed = discord.Embed(color=0xe74c3c)
    embed.description = f'❌ **Error**\n'

    if event == 'on_command_error':
        embed.description += (f'```ahk\n{args[1]}```\n[Message]({args[0].message.jump_url}) ' +
                              f'by {args[0].message.author.mention} `{args[0].message.author.name}#{args[0].message.author.discriminator}` ' +
示例#27
0
    if ctx.message.guild is None or ctx.prefix.startswith(ctx.bot.user.mention):
        if exc_type is commands.CommandNotFound:
            await ctx.send(str(exc))
            return

    # from the original command error function
    print('Ignoring exception in command {}'.format(ctx.command), file=sys.stderr)
    traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)

if __name__ == '__main__':
    setup_logging()

    # Ensure database folder exists
    os.makedirs('database', exist_ok=True)

    prefixes = commands.when_mentioned_or('!')
    description = "Supe's glorious and handsome bot"

    tagdb = core.TagDatabase()

    bot = commands.Bot(command_prefix=prefixes, description=description)
    bot.on_command_error = command_error
    bot.add_cog(plugins.AdministrativePlugin(bot))
    bot.add_cog(plugins.MusicPlayerPlugin(bot, tagdb))
    bot.add_cog(plugins.TagPlugin(bot, tagdb))
    bot.add_cog(plugins.RandomGamePlugin(bot, config.games))

    logging.info("Bot plugins initialized")
    bot.run(config.credentials)
    logging.info("Bot shut down")
示例#28
0
import asyncio
import os
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from mongodb_connector import MongoDBConnector
from checks import get_amount, is_DM, fine_paid_message, remove_bots

desc = 'A bot made by Mayukh to manage expenses, Interact with the bot only in the expenses channel'

db_name = 'manager_db'
loop = asyncio.get_event_loop()
db_connector = MongoDBConnector(os.getenv('MONGODB_SRV'),
                                db_name='manager_db',
                                loop=loop)
bot = Bot(command_prefix=commands.when_mentioned_or("$"),
          description=desc,
          loop=loop)
bot.remove_command('help')


@bot.event
async def on_guild_remove(guild):
    """Will remove this guilds Data from DB"""
    await db_connector.remove_guild(guild_id=guild.id)


@bot.event
async def on_guild_join(guild):
    """Add this guild in DB"""
    await db_connector.create_guild(name=guild.name, guild_id=guild.id)
示例#29
0
# Notify.py

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from discord.utils import get

load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
client = discord.Client()


class CustomBot(commands.Bot):
    async def on_ready(self):
        print(f'{self.user} is ready to notify!')


bot = CustomBot(command_prefix=commands.when_mentioned_or("!"))
示例#30
0
 async def _prefix_or_mention(bot, message):
     prefix = await pegar_o_prefixo(bot, message)
     return commands.when_mentioned_or(prefix)(bot, message)
示例#31
0
文件: bot.py 项目: Ispira/Ispyra
log_file     = config["log_file"]
log_messages = config["log_messages"]
log_commands = config["log_commands"]
cmd_on_edit  = config["commands_on_edit"]

# Grab the blacklist
with open("db/blacklist.json") as bl:
    blacklist = json.load(bl)["users"]

log = get_logger(log_file)

# Set the bot and basic variables up
description="""
General purpose chat and administration bot.
"""
bot = c.Bot(c.when_mentioned_or(prefix), pm_help=True, description=description)
plugins = []
first_launch = True

# Helper function to load plugins
def load_plugins():
    for p in os.listdir("plugins"):
        if p.endswith(".py"):
            p = p.rstrip(".py")
            try:
                bot.load_extension(f'plugins.{p}')
                plugins.append(p)
            except Exception as error:
                exc = "{0}: {1}".format(type(error).__name__, error)
                log.warning(f"Failed to load plugin {p}:\n    {exc}")
    first_launch = False
示例#32
0
文件: main.py 项目: xiecie/modmail
def _get_guild_prefix(bot2, message):
    prefix = get_guild_prefix(bot2, message.guild)
    return commands.when_mentioned_or(prefix)(bot2, message)
示例#33
0
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='/root/discord/files/discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

# --------------------------Bot Stuff Under Here--------------------------
path.insert(0, '.')

description = '''NotSoSuper\'s Super Duper Bot'''
owner = "130070621034905600"
bot = commands.Bot(command_prefix=commands.when_mentioned_or('.'), description=description, help_attrs={'name':"iamabadhelpcommand", 'enabled':False, 'hidden':True})
code = "```py\n{0}\n```"
cool = "```xl\n{0}\n```"
starttime = time.time()
starttime2 = time.ctime(int(time.time()))

if os.path.isfile("/root/discord/utils/blacklist.txt"):
    pass
else:
    with open("/root/discord/utils/blacklist.txt","a") as f:
        f.write("")

modules = [
    'mods.Moderation',
    'mods.Utils',
    'mods.Info',
示例#34
0
 async def prefix(self, bot, message):
     prefixes = ["gen "]
     if message.guild is None:
         return ""
     else:
         return cmd.when_mentioned_or(*prefixes)(bot, message)
    @asyncio.coroutine
    def on_message(self, message):
        if message.author == self.user:
            return

        elif "sneak peak" in message.clean_content.lower():
            """ If anybody says sneak peak, let them know """
            yield from self.send_message(message.channel, 'I think you mean "sneak peek".')

        else:
            yield from self.process_commands(message)

""" Set the bot information for login """
description = ("I'm a discord bot based on the original Stealth Mountain: "
    "twitter.com/stealthmountain. I'm one sneaky peak.")
bot = StealthMountainBot(command_prefix=commands.when_mentioned_or('^^'), description=description)
with open('auth.json', 'r') as authfile:
    auths = json.load(authfile)


@bot.event
async def on_ready():
    """ When the bot is up and running, print its username and id
        to the console. """
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

bot.run(auths["token"])
示例#36
0
def get_prefix(bot, message):
    prefixes = [',']
    if not message.guild:
        return ','
    return commands.when_mentioned_or(*prefixes)(bot, message)
示例#37
0
from discord.ext import commands
from cogs.utils import utilities

import re

debug = False
information = "Ruby Bot, your one-stop solution for music queueing! (Now updated with commands.ext)\nCreated with 100% stolen code from Chezz and link2110.\nThank you for using Ruby Bot!"
initial_extensions = ['cogs.administrative', 'cogs.music', 'cogs.info', 'cogs.memes', 'cogs.streams']
if debug:
    bot = commands.Bot(command_prefix=commands.when_mentioned_or('+'), description=information)
else:
    bot = commands.Bot(command_prefix=commands.when_mentioned_or('~'), description=information)


@bot.event
async def on_ready():
    print('Logged in as:\n{0} (ID: {0.id})'.format(bot.user))


@bot.event
async def on_error(event, *args, **kwargs):
    print(event)
    print(str(args))
    print(str(kwargs))


@bot.event
async def on_message(message):
    ch = message.channel
    msg = message.content.lower()
    # If the string contains "aquors" and is NOT preceded by a letter and is NOT followed by a letter
示例#38
0
def get_prefix(client, message):
    prefixes = ['$']    # sets the prefixes, u can keep it as an array of only 1 item if you need only one prefix
    if not message.guild:
        prefixes = ['$']   # Only allow '==' as a prefix when in DMs
    return commands.when_mentioned_or(*prefixes)(client, message)    # Allow users to @mention the bot instead of using a prefix when using a command.
示例#39
0
文件: bot.py 项目: Maverun/Nurevam
from discord.ext import commands
from discord import errors
from cogs.utils import utils
import traceback
import datetime
import storage
import discord
import glob

import helpformat

description = '''Nurevam's Command List. '''
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), description=description,help_attrs=dict(pm_help=False,hidden=True),formatter=helpformat.Custom_format())
bot.db= storage.Redis()
redis = utils.redis

def check_post(check):
    if check == "None":
        return None
    elif check == "on":
        return 30

async def say(ctx,**kwargs):
    print("at say function",ctx,kwargs)
    check = await bot.db.redis.hget("{}:Config:Delete_MSG".format(ctx.message.guild.id),ctx.command.cog_name.lower())
    return await ctx.send(**kwargs,delete_after=check_post(check))

bot.say=say

@bot.event
async def on_ready():
示例#40
0
        elif voter.id not in state.skip_votes:
            state.skip_votes.add(voter.id)
            total_votes = len(state.skip_votes)
            if total_votes >= 3:
                await self.bot.say('Skip vote passed, skipping song...')
                state.skip()
            else:
                await self.bot.say('Skip vote added, currently at [{}/3]'.format(total_votes))
        else:
            await self.bot.say('You have already voted to skip this song.')

    @commands.command(pass_context=True, no_pm=True)
    async def playing(self, ctx):
        """Shows info about the currently played song."""

        state = self.get_voice_state(ctx.message.server)
        if state.current is None:
            await self.bot.say('Not playing anything.')
        else:
            skip_count = len(state.skip_votes)
            await self.bot.say('Now playing {} [skips: {}/3]'.format(state.current, skip_count))

bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description='A playlist example for discord.py')
bot.add_cog(Music(bot))

@bot.event
async def on_ready():
    print('Logged in as:\n{0} (ID: {0.id})'.format(bot.user))

bot.run('token')
示例#41
0
import discord
from discord.ext import commands
import asyncio

import logging
import os

#import cogs
from spoopycogs.soundboard import Soundboard

TOKEN = os.environ['DISCORD_SPOOPY_TOKEN']

logging.basicConfig(level=logging.INFO)

bot = commands.Bot(command_prefix=commands.when_mentioned_or('.'), description='SpoopyBot')

print("Discord.py version is " + discord.__version__)

if not discord.opus.is_loaded():
	discord.opus.load_opus('libopus.so')
print("Opus successfully loaded: " + str(discord.opus.is_loaded()))

bot.add_cog(Soundboard(bot))

@bot.event
async def on_ready():
	print("Logged in as {0} (ID: {0.id})".format(bot.user))

bot.run(TOKEN)
示例#42
0
def get_prefix(bot, message):
    prefix = db.field(
        "SELECT Prefix FROM guilds WHERE GuildID = ?", message.guild.id)
    return when_mentioned_or(prefix)(bot, message)
示例#43
0
import configparser
import os

from discord.ext import commands as cmds

from src.basicbot import BasicBot
from src.cogs import *

config = configparser.RawConfigParser()
config_file = os.path.dirname(os.path.realpath(__file__)) + "/../tnybot_config"
config.read(config_file)


oauthbot = BasicBot(command_prefix=cmds.when_mentioned_or("!"))

oauthbot.add_cog(Reaction(oauthbot))
oauthbot.add_cog(Commands(oauthbot))
oauthbot.add_cog(CustomCommands(oauthbot))
oauthbot.add_cog(Greetings(oauthbot))
oauthbot.add_cog(Logs(oauthbot))
oauthbot.add_cog(Stats(oauthbot))
oauthbot.add_cog(Notifications(oauthbot, config_file=config_file))
# oauthbot.add_cog(Roles(oauthbot, db_url=config["Postgres"]["URL"]))
oauthbot.add_cog(Reminders(oauthbot, config["TimeZone"]["tz"]))
oauthbot.run(config["OAuth"]["token"])
示例#44
0
import configparser
import os

from discord.ext import commands as cmds

from src.basicbot import BasicBot

config = configparser.RawConfigParser()
config_file = os.path.dirname(os.path.realpath(__file__)) + "/../tnybot_config"
config.read(config_file)

tnybot = BasicBot(name="TnyBot", command_prefix=cmds.when_mentioned_or("#!"))

# Tuple of the path to the cog file, and the extra args it takes
cogs = [
    ("cogs.commands", {}),
    ("cogs.custom_commands", {}),
    ("cogs.greetings", {}),
    ("cogs.logs", {}),
    ("cogs.music", {}),
    ("cogs.notifications", {"config_file": config_file}),
    ("cogs.reaction", {}),
    ("cogs.reminders", {"tz": config["TimeZone"]["tz"]}),
    ("cogs.vlive", {}),
]

tnybot.load_cogs(cogs)

tnybot.run(config["User"]["user"], config["User"]["pass"])
示例#45
0
from discord.ext import commands
import os, json

information = 'Laxatives'

extensions = {'cogs.twitter', 'cogs.discord'}
bot = commands.Bot(description=information, self_bot=False, command_prefix=commands.when_mentioned_or('$'))


def load_credentials():
    path = os.path.join(os.getcwd(), 'files', 'credentials.json')
    with open(path) as f:
        return json.load(f)


credentials = load_credentials()

if __name__ == "__main__":
    for extension in extensions:
        bot.load_extension(extension)

    token = credentials['discord']['token']
    while True:
        try:
            bot.run(token, bot=True)
        except Exception:
            pass
示例#46
0
文件: bot.py 项目: qvalador/qsprite
import discord
import asyncio
import os

from discord.ext import commands
from conf import *

description = """yet another niche, general(?)-purpose discord bot for qvalador.  hey, how'd you find this description, anyway?"""

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or('qq '), description=description)

VERSION = "1.0.0"


def update_avatar(filename):
    """updates the avatar to the provided file name."""
    if os.path.isfile(filename):
        with open(filename, "rb") as avatar:
            bot.edit_profile(avatar=avatar.read())


def load_cogs():
    for subdir in next(os.walk(cog_dir))[1]:
        try:
            bot.load_extension("cogs.{}.cog".format(subdir))
            print("loaded plugin: {}".format(subdir))
        except Exception as error:
            exception = "{0}: {1}".format(type(error).__name__, error)
            print("Failed to load {}: {}".format(subdir, exception))
示例#47
0
# -*- coding: utf-8 -*-

import discord
from discord.ext import commands, timers
import random
import json
import os
import asyncio
import datetime
from random import randint

# config stuff
token = str(os.environ['DISCORD_API_TOKEN'])
random_joins = str(os.environ['ENABLE_RANDOM_JOINS']).lower()
logging_channel = int(os.environ['LOGGING_CHANNEL'])
client = commands.Bot(command_prefix=commands.when_mentioned_or("!"),
                      description='Buttergolem Discord Bot')
client.timer_manager = timers.TimerManager(client)


# simple log function
async def _log(message):
    channel = client.get_channel(logging_channel)
    await channel.send(
        "```\n" + datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S # ") +
        str(message) + "```\n")


# Do this on ready (when joining)
@client.event
async def on_ready():
示例#48
0
文件: __main__.py 项目: bendiller/bot
import asyncio
import logging
import socket

import discord
from aiohttp import AsyncResolver, ClientSession, TCPConnector
from discord.ext.commands import Bot, when_mentioned_or

from bot import patches
from bot.api import APIClient, APILoggingHandler
from bot.constants import Bot as BotConfig, DEBUG_MODE

log = logging.getLogger('bot')

bot = Bot(
    command_prefix=when_mentioned_or(BotConfig.prefix),
    activity=discord.Game(name="Commands: !help"),
    case_insensitive=True,
    max_messages=10_000,
)

# Global aiohttp session for all cogs
# - Uses asyncio for DNS resolution instead of threads, so we don't spam threads
# - Uses AF_INET as its socket family to prevent https related problems both locally and in prod.
bot.http_session = ClientSession(connector=TCPConnector(
    resolver=AsyncResolver(),
    family=socket.AF_INET,
))
bot.api_client = APIClient(loop=asyncio.get_event_loop())
log.addHandler(APILoggingHandler(bot.api_client))
示例#49
0
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import discord
import json

startup_extensions = ["help", "moderation", "general", "featured"]

bot = Bot (command_prefix=commands.when_mentioned_or('%'))

@bot.event
async def on_command_error(error, ctx):
        cmd = ctx.command
        if isinstance(error, commands.BadArgument):
        	await bot.send_message(ctx.message.channel, "**ERROR in the Command {}:**```py\n{}```".format(cmd, error))
        if isinstance(error, commands.CommandInvokeError):
        	await bot.send_message(ctx.message.channel, "**ERROR in the Command {}:**```py\n{}```".format(cmd, error))
        if isinstance(error, commands.CommandOnCooldown):
        	await bot.send_message(ctx.message.channel, "⏱ **This command is currently under cooldown. Try again in {:.2f} hours!**".format(error.retry_after / 3600))
        else:
            print(error)

@bot.event
async def on_ready():
	print('Logged in as '+bot.user.name+' (ID:'+bot.user.id+') | Connected to '+str(len(bot.servers))+' servers | Connected to '+str(len(set(bot.get_all_members())))+' users')
	print('--------')
	return await bot.change_presence(game=discord.Game(name='Bots for Discord', type=3))

@bot.event
async def on_message(message):
    allowed = ["308358617458016256", "374071874222686211", "374074135506190349"]
示例#50
0
async def get_prefix(the_bot, message):
    if not message.guild:
        return commands.when_mentioned_or(config.DEFAULT_PREFIX)(the_bot,
                                                                 message)
    gp = await the_bot.get_guild_prefix(message.guild)
    return commands.when_mentioned_or(gp)(the_bot, message)
示例#51
0
def prefix(client, message):
    prefixes = ['!', '']
    if message.guild:
        prefixes = ['!']
    return commands.when_mentioned_or(*prefixes)(client, message)
示例#52
0
from Cogs import Admin
from Cogs import Channel
from Cogs import Feed
from Cogs import Reddit
from Cogs import Comic
from Cogs import Lists
from Cogs import Bot
from Cogs import Example
from Cogs import Humor
from Cogs import Help
from Cogs import Uptime
from Cogs import MadLibs
from Cogs import DrBeer

# This should be the main soul of the bot - everything should load from here
bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'),
                   description='A bot that does stuff.... probably')
# Initialize some things
jsonFile = "Settings.json"
# Open our token
with open('token.txt', 'r') as f:
    token = f.read()

# Create our cog classes
cogList = []

# Settings
settings = Settings.Settings(bot, jsonFile)
cogList.append(settings)

# Examples - there are 2 parts here, Example, and Music
示例#53
0
        await ctx.bot.send_message(ctx.message.channel, "No wonder you're horrible at debates with arguments like that")
        return

    if ctx.message.server is None or ctx.prefix.startswith(ctx.bot.user.mention):
        if exc_type is commands.CommandNotFound:
            await ctx.bot.send_message(ctx.message.channel, str(exc))
            return

    # from the original command error function
    print('Ignoring exception in command {}'.format(ctx.command), file=sys.stderr)
    traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)

if __name__ == '__main__':
    # Ensure database folder exists
    os.makedirs('database', exist_ok=True)

    prefixes = commands.when_mentioned_or('!')
    description = "Supe's glorious and handsome bot"

    tagdb = core.TagDatabase()

    bot = commands.Bot(command_prefix=prefixes, description=description)
    bot.on_command_error = command_error
    bot.add_cog(plugins.AdministrativePlugin(bot))
    bot.add_cog(plugins.MusicPlayerPlugin(bot, tagdb))
    bot.add_cog(plugins.ChoicePlugin(bot))
    bot.add_cog(plugins.TagPlugin(bot, tagdb))
    bot.add_cog(plugins.RandomGamePlugin(bot, config.games))

    bot.run(config.credentials)
示例#54
0
文件: main.py 项目: atli164/Goldibot
#! /usr/bin/python3

import discord
from discord.ext import commands
import os
import importlib
import sys
import config
import secrets

bot = commands.Bot(command_prefix = commands.when_mentioned_or(*config.prefixes), 
		   description = config.description) 

@bot.event
async def on_ready():
	print('Login successful')
	print('User: '******'ID: ' + str(bot.user.id))
	await bot.change_presence(activity=discord.Game(name='by herself'))

@bot.command(pass_context=True)
async def kill(ctx):
	"""Turns off the bot. Only usable by Goldilocks.\nThis command takes no input."""
	if ctx.message.author.id == '249293986349580290':
		print('Turning off... Bye!')
		sys.exit()

def load_ext(bot, name, settings):
    lib = importlib.import_module(name)
    if not hasattr(lib, 'setup'):
        print(lib)
示例#55
0
        ctx = commands.context.Context(**tmp)
        del tmp

        if invoker in self.commands:
            command = self.commands[invoker]
            self.dispatch('command', command, ctx)
            ctx.command = command
            yield from command.invoke(ctx)
            self.dispatch('command_completion', command, ctx)
        else:
            exc = commands.CommandNotFound('Command "{}" is not found'.format(invoker))
            self.dispatch('command_error', exc, ctx)


description = """I am a whois bot made by alfalfascout on GitHub to help you keep track of your users' descriptions and pronouns until Discord adds official profiles or something."""
bot = Botso(command_prefix=commands.when_mentioned_or("%"),
    formatter=BotsoFormatter(), description=description)


initial_extensions = [
    "cogs.general",
    "cogs.usies"
]


for extension in initial_extensions:
    try:
        bot.load_extension(extension)
    except Exception as e:
        print('Failed to load extension {}\n{}: {}'.format(extension, type(e).__name__, e))
示例#56
0
import aiosqlite
import discord
from discord.ext import commands
from discord.ext.commands import when_mentioned_or

from core import constants
from core.monitoring import (RSS, Google_Alerts, Reddit, Telegram, Twitter,
                             YouTube)

bot = commands.Bot(activity=discord.Game(name="Pwning The Jewels"),
                   case_insensitive=False,
                   command_prefix=when_mentioned_or(constants.Bot.prefix),
                   help_command=None,
                   max_messages=10000)


# Runs this function once the bot is ready.
@bot.event
async def on_ready():
    """
    The database here will be used to store the items to be tracked.
    Upon running the bot for the first time, the database and its tables will be created.
    """
    async with aiosqlite.connect(constants.Database.name) as database:
        # Create general RSS related tables:
        await database.execute(
            "CREATE TABLE IF NOT EXISTS general_rss_links(url TEXT)")
        await database.execute(
            "CREATE TABLE IF NOT EXISTS general_rss_posts(id TEXT, title TEXT, url TEXT)"
        )
示例#57
0
import asyncio
import discord
from MusicFct import *
from discord.ext import commands

Beta = True

if not discord.opus.is_loaded():
    # the 'opus' library here is opus.dll on windows
    # or libopus.so on linux in the current directory
    # you should replace this with the location the
    # opus library is located in and with the proper filename.
    # note that on windows this DLL is automatically provided for you
    discord.opus.load_opus('opus')
if Beta:
	bot = commands.Bot(command_prefix=commands.when_mentioned_or('€'), description='Je suis le bot du serveur discord French Baguette, voici les commandes que vous pouvez utiliser sur moi: ')
else:
	bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description='Je suis le bot du serveur discord French Baguette, voici les commandes que vous pouvez utiliser sur moi: ')
bot.add_cog(Music(bot))

@bot.event
async def on_ready():
    print('Logged in as:\n{0} (ID: {0.id})'.format(bot.user))

if Beta:
	bot.run('Token')
else:
	bot.run('Token')
示例#58
0
文件: dog.py 项目: fabianod/dogbot
root_logger.addHandler(stream)
root_logger.addHandler(file_handler)
root_logger.addHandler(file_sane_handler)

logger = logging.getLogger('dog')

logger.info('bot starting')

# gather additional options from the configuration file
additional_options = getattr(cfg, 'options', {})
additional_options.update({'owner_id': getattr(cfg, 'owner_id', None)})

logger.info('bot options: %s', additional_options)

# create dogbot instance
d = DogBot(command_prefix=commands.when_mentioned_or(*cfg.prefixes),
           **additional_options)


def ext_filter(f):
    return f not in ('__init__.py', '__pycache__') and not f.endswith('.pyc')


exts = []

# walk the ext directory to find extensions
for path, dirs, files in os.walk('dog/ext'):
    exts += [
        path.replace('/', '.') + '.' + file.replace('.py', '')
        for file in filter(ext_filter, files)
    ]