def kick_user(user, mod, server, bot, reason):
"""
Kicks a user and then logs it to the 'mod_log' channel
:param user: Member object of the user who needs to be kicked
:param mod: Member object of the responsible moderator
:param server: Server object of the server
:param bot: Bot instance to kick and log
:param reason: Reason why user is being kicked
"""
config = bot.cogs['Config']
channel = get_channel_by_name(server, config['aryas']['mod_log_channel_name'])
try:
await bot.kick(user)
msg = '{} was kicked by {}. Reason: {}'.format(user.name, mod.mention, reason)
send(bot, msg, channel, False)
except Exception as e:
config.logger.error(e)
send(bot, 'Failed to kick {} for {}'.format(user.mention, reason), channel, False)
python类Bot()的实例源码
def send(bot: commands.Bot, message: str, channel: Channel, delete=False,
time=None, show_dots=True, bomb_themed_dots=False) -> None:
"""
Sends a message to the server and deletes it after a period of time
:param bot: the bot used to send the message
:param message: the content of the message
:param channel: the channel in which the message will be sent
:param delete: whether to delete the message after sending it
:param time: the time to wait before deleting the message
:param show_dots: whether to show countdown dots for message deletion (this will round down `time` if it is a float)
:param bomb_themed_dots: whether to theme the dots using a bomb and fuse instead of plain dots
"""
config = bot.cogs['Config']
if time is None:
time = config['aryas']['message_sleep_time']
def dot_bar(progress):
width = int(time)
if bomb_themed_dots:
return "\n`??" + "-" * (width - progress) + "*`" if width - progress > 0 else "??"
return "\n`|" + "•" * (width - progress) + " " * max(progress, 0) + "|`"
async def send_inner():
msg = await bot.send_message(channel, message + (dot_bar(0) if delete and show_dots else ""))
# Waits *time* seconds and deletes the confirmation message.
if delete:
if not show_dots:
await asyncio.sleep(time)
else:
for i in range(int(time)):
await asyncio.sleep(1)
await bot.edit_message(msg, message + dot_bar(i + 1))
await bot.delete_message(msg)
asyncio.ensure_future(send_inner())
def is_staff(member: discord.Member):
# Return True or False if User is a Staff Member
return 'Staff' in [r.name for r in member.roles]
# ********************************************** #
# BOT EVENTS *********************************** #
# ********************************************** #
# Bot Start Event
def __init__(self, *args, **kwargs):
"""In addition to everything supported by commands.Bot, this also supports:
* `config_file` - An `str` representing the configuration file of the bot. Defaults to
`config.json`. This doesn't really have to be used, but it's there for
convenience reasons.
Instance variables not in the constructor:
* `session` - An `aiohttp.ClientSession` that the bot can use to make HTTP requests.
This is useful for commands that perform API hooks.
* `config` - A `dict` containing key-value pairs meant for bot configuration. This doesn't
really have to be used, but it's there for convenience reasons.
"""
super().__init__(*args, **kwargs)
self.config = {}
self.config_file = kwargs.get("config_file", "config.json")
self.session = aiohttp.ClientSession(loop=self.loop)
def load_config(self, filename: str=None):
"""Load config from a JSON file.
* `filename` - The filename of the JSON file to be loaded. If not specified, the bot will
default to `Bot.config_file`.
"""
if not filename:
filename = self.config_file
with open(filename) as file_object:
config = json.load(file_object)
if isinstance(config, dict):
for key, value in config.items():
self.config[key] = value
def save_config(self, filename: str=None):
"""Save config to a JSON file.
* `filename` - The filename of the JSON file to be saved to. If not specified, the bot will
default to `Bot.config_file`.
"""
if not filename:
filename = self.config_file
with open(filename, "w") as file_object:
json.dump(self.config, file_object, indent=4, sort_keys=True)
def colour(self):
brole = discord.utils.get(self.bot.get_server('226084200405663754').roles, name = 'Bot')
bcol = brole.colour
erole = discord.utils.get(self.bot.get_server('226084200405663754').roles, name = '@everyone')
ecol = erole.colour
curole = discord.utils.get(self.bot.get_server('226084200405663754').roles, name = 'Bot Dev')
cucol = curole.colour
if cucol == bcol:
await self.bot.edit_role(self.bot.get_server('226084200405663754'), curole, colour = ecol)
else:
await self.bot.edit_role(self.bot.get_server('226084200405663754'), curole, colour = bcol)
def on_ready():
global mainChannel, logsChannel, visible, databasePath, botOwner, Refresh
mainChannel = client.get_server(constants.Settings.mainServerID).get_channel(constants.Settings.mainChannelId)
logsChannel = client.get_server(constants.Settings.mainServerID).get_channel(constants.Settings.logsChannelId)
print('Logged in !')
botOwner = await client.get_user_info(str(constants.Settings.ownerDiscordId))
hello = False
if (datetime.now().strftime('%H') == "02" and Refresh) or ((set(sys.argv) & set(["refresh"])) and Refresh):
await change_presence(status=discord.Status('dnd'), game=discord.Game(name='Booting ...'))
message = await client.send_message(mainChannel, "<:empty:317951266355544065> Updating stats ...")
#try:
print('Refreshing users stats ...')
update_stats.update_all_stats(conn, cursor)
Refresh = False
print(" - Done")
print('Creating new backup ...', end="")
create_backup()
print(" Done !")
await client.edit_message(message, "<:check:317951246084341761> Updating stats ... Done !")
# except:
# await client.edit_message(message, "<:xmark:317951256889131008> Updating stats ... Fail !")
if not set(sys.argv) & set(["dev"]):
await client.send_message(mainChannel, "<:online:317951041838514179> Uso!<:Bot:317951180737347587> is now online !")
await change_presence(status=discord.Status('online'), game=discord.Game(name='Osu !'))
hello = True
if (set(sys.argv) & set(["online"])) and hello == False:
await client.send_message(mainChannel, "<:online:317951041838514179> Uso!<:Bot:317951180737347587> is now online !")
if set(sys.argv) & set(["dev"]):
await change_presence(status=discord.Status('idle'), game=discord.Game(name='Dev mode'))
else:
await change_presence(status=discord.Status('online'), game=discord.Game(name='o!help'))
print ('Ready !')
def __init__(self,token):
self.client = commands.Bot(command_prefix=commands.when_mentioned_or('!'),description=clientDesc)
self.token = token
#------------------------Setting up cogs---------------------------------------------------------
#setup_ow(self.client)
setup_misc(self.client)
#setup_game(self.client)
setup_music(self.client)
#setup_twitch(self.client)
def github(ctx):
"""Pour voir mon code"""
text = "How tu veux voir mon repos Github pour me disséquer ? Pas de soucis ! Je suis un Bot, je ne ressens pas la douleur !\n https://github.com/outout14/tuxbot-bot"
em = discord.Embed(title='Repos TuxBot-Bot', description=text, colour=0xE9D460)
em.set_author(name='Outout', icon_url="https://avatars0.githubusercontent.com/u/14958554?v=3&s=400")
await ctx.send(embed=em)
def get_cog(self, name):
return self.all_cogs.get(name.lower())
# This must be implemented because Bot.get_all_commands doesn't call
# Bot.get_cog, so it will throw KeyError, and thus return an empty set.
def on_command_completion(self, ctx):
self.command_counter['succeeded'] += 1
# ------ Viewlikes ------
# Note these views and properties look deceptive. They look like a thin
# wrapper len(self.guilds). However, the reason why these are here is
# to avoid a temporary list to get the len of. Bot.guilds and Bot.users
# creates a list which can cause a massive hit in performance later on.
def on_command_error(self, context, exception):
extype = type(exception)
value = exception
tback = exception.__traceback__
exinfo = (extype, value, tback)
exfmts = [s.replace("\\n", "") for s in traceback.format_exception(*exinfo)]
exfmt = [""]
for exf in exfmts:
ci = len(exfmt) - 1
if len(exfmt[ci]) + len(exf) + 1 > 1024:
exfmt.append(exf)
else:
exfmt[ci] = exfmt[ci] + "\n" + exf
if context.command is None:
return
cmd = context.command.qualified_name
iex = exception.original if isinstance(exception, commands.CommandInvokeError) else None
if iex and isinstance(iex, asmbot.AssemblerException):
embed = self._embed(context, "Error assembling code", "An error occured when assembling code", "error")
embed.add_field(name="Details", value=f"```\n{iex.clang_data}\n```", inline=False)
else:
embed = self._embed(context, "Error executing command", "An error occured when executing command `{}`".format(cmd), "error")
asmbot.log(*exfmts, tag="CMD ERR")
await context.message.channel.send(embed=embed)
# Bot preparation
def __init__(self, bot: commands.Bot):
self.bot = bot
self.api_url = 'http://api.football-data.org/v1/'
self.config = dataIO.load_json('data/football/config.json')
def __init__(self, bot: Bot, database: Database):
super().__init__(bot)
self.database = database
def play_audio(self, data, *, encode=True):
pass
#
# Main DdmBot class (discord.ext.commands.Bot wrapper)
#
def __init__(self, bot: commands.Bot):
super().__init__()
self.categories = ['hot', 'new', 'controversial', 'rising', 'top']
self.bot = bot
def on_ready():
print('Logged in as ')
print(bot.user.name)
print(bot.user.id)
print('Bot prefix is set to ' + prefix)
print('-------------')
await bot.change_presence(game=discord.Game(name='with systemd'))
await decayWarn()
def killbot(ctx):
"""Kills the selfbot"""
print("Shutting down selfbot")
await bot.say(embed=discord.Embed(title="Bot Status", type="rich", timestamp=datetime.utcnow(), colour=0x747F8D, description="Shutting down bot..."))
await bot.close()
def setup(bot: commands.Bot):
bot.add_cog(MIDI(bot))