为什么我的机器人在我键入命令时会发送命令输出?

时间:2021-02-24 18:13:03

标签: python python-3.x discord.py

今天我去使用我的机器人,当我输入命令时,它开始向输出发送垃圾邮件,没有停止,之后也不会响应任何内容。另外,我在终端中没有错误。有人能帮我吗?我也不记得我的代码有任何重大更改,例如添加新功能和类似的东西。我不知道发生了什么。

import discord
import json
import random
import os 
import sys
import string
from discord.ext import commands, tasks
from itertools import cycle
import pickle
import asyncio
from discord.ext.commands import CommandNotFound
import subprocess

def get_prefix(client, message):
    with open('prefixes2.json', 'r') as f:
        prefixes = json.load(f)

    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix, help_command=None)
status = cycle(['Python 3.8', 'as-help for help', 'with members', 'GD and being pog', 'with TheSuperRobert', 'on a Raspberry Pi'])

with open("badwords2.txt") as file:
    bad_words = file.read().splitlines()

@client.event
async def on_message(message):    
    for bad_word in bad_words:
        if bad_word in message.content.lower().split(" "):
            t = discord.Embed(color=0x039e00, title="Message Removed", description=f":x:   Please don't say that here, {message.author.mention}.")
            t.set_footer(text="DM TheSuperRobert2498#2498 for bot suggestions.")
            await message.channel.send(embed=t, delete_after=3)
            await message.delete()
            break
        else:
            await client.process_commands(message)

@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(status=discord.Status.dnd, activity=discord.Game(next(status)))

@client.event
async def on_ready():
    change_status.start()
    print("bot is now fully online.")

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, CommandNotFound):
        await ctx.send(f":x: That's not a command! Please enter a valid command, {ctx.author.mention}.")

@client.event
async def on_guild_join(guild):
    with open('prefixes2.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = 'as-'

    with open('prefixes2.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes2.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes2.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.command()
@commands.has_guild_permissions(administrator=True)
async def prefix(ctx, prefix):
    with open('prefixes2.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open('prefixes2.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

    await ctx.send(f'Prefix changed to `{prefix}`.')

@prefix.error
async def prefix_error(ctx):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f":x:  You don't have permission to use this command, {ctx.author.mention}.")

@client.command()
@commands.has_guild_permissions(manage_messages=True)
async def clear(ctx, amount=1):
    await ctx.channel.purge(limit=amount)

@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'Please specify how many messages you want deleted, {ctx.author.mention}.')

@client.command()
@commands.has_guild_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason=None):
    await member.ban(reason=reason)
    embed=discord.Embed(title=f"Member Banned", description=f"{member} has been banned.")
    embed.add_field(name=f"Moderator", value=f"{ctx.message.author}", inline=True)
    embed.add_field(name=f"Reason", value=f"{reason}", inline=True)
    await ctx.send(embed=embed)
    
@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
@commands.has_guild_permissions(kick_members=True)
async def kick(ctx, member : discord.Member, *, reason=None):
    await member.kick(reason=reason)
    embed=discord.Embed(title=f"Member Kicked", description=f"{member} has been kicked from {ctx.guild.name}.")
    embed.add_field(name=f"Moderator", value=f"{ctx.message.author}", inline=True)
    embed.add_field(name=f"Reason", value=f"{reason}", inline=True)
    await ctx.send(embed=embed)
    await ctx.send(f"{reason}")

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
@commands.has_guild_permissions(kick_members=True)
async def mute(ctx, member : discord.Member, *, reason=None):
    role = discord.utils.get(ctx.guild.roles, name='Muted')
    await ctx.add_roles(role)
    embed=discord.Embed(title=f"Member Muted", description=f"{member} has been muted indefinitely.")
    embed.add_field(name=f"Moderator", value=f"{ctx.message.author}", inline=True)
    embed.add_field(name=f"Reason", value=f"{reason}", inline=True)

@mute.error
async def mute_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
@commands.has_guild_permissions(kick_members=True)
async def tempmute(ctx, member: discord.Member, time, *, reason=None):
    muted_role = discord.utils.get(ctx.guild.roles, name="Muted")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400, "w":604800, "mo":2592000, "y":31104000}
    tempmute = int(time[:-1]) * time_convert[time[-1]]
    await member.add_roles(muted_role)
    embed=discord.Embed(title=f"Member Muted", description=f"{member} has been muted for {time}.")
    embed.add_field(name=f"Moderator", value=f"{ctx.message.author}", inline=True)
    embed.add_field(name=f"Reason", value=f"{reason}", inline=True)
    await ctx.send(embed=embed)
    await asyncio.sleep(tempmute)
    await member.remove_roles(muted_role)

@tempmute.error
async def tempmute_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
@commands.has_guild_permissions(kick_members=True)
async def unmute(ctx, member : discord.Member, *, reason=None):
    role = discord.utils.get(ctx.guild.roles, name='Muted')
    await member.remove_roles(role)
    await ctx.send(f'Unmuted {member.mention}.')

@unmute.error
async def unmute_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name,member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            
        
        if (user.mention) == (user.mention):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

@unban.error
async def unban_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f" :x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
async def invite(ctx):
    await ctx.send("https://discord.com/api/oauth2/authorize?client_id=760992484897193984&permissions=8&scope=bot")

@client.command()
@commands.is_owner()
async def restart(ctx):
    await ctx.send('Restarting bot.')
    os.execl(sys.executable, sys.executable, *sys.argv)
    await ctx.send('Restart complete.')

@restart.error
async def restart_error(ctx, error):
    if isinstance(error, commands.NotOwner):
        await ctx.send(":x:  Only the owner of this bot can use this command.")

@client.command()
@commands.is_owner()
async def shutdown(ctx):
    await ctx.send("Shutting down bot.")
    await client.logout()

@shutdown.error
async def shutdown_error(ctx, error):
    if isinstance(error, commands.NotOwner):
        await ctx.send(":x:  Only the owner of this bot can use this command.")

@client.command()
async def servers(ctx):
    await ctx.send(f"Bot is in {len(client.guilds)} servers!")

@client.command(aliases=['8ball', 'magic8ball', 'magiceightball', '8b'])
async def eightball(ctx, member):
    responses = [f'Try again later, {ctx.message.author.mention}.',
                 f'No, {ctx.message.author.mention}.',
                 f'Yes, {ctx.message.author.mention}.',
                 f'It is not certain, {ctx.message.author.mention}.',
                 f'Definetely not, {ctx.message.author.mention}.',
                 f'Of course, {ctx.message.author.mention}.',
                 f"I don't know, try again, {ctx.message.author.mention}.",
                 f'It is most certain, {ctx.message.author.mention}.',
                 f'ERROR: Try again, {ctx.message.author.mention}.',
                 f'Nope, not happening, {ctx.message.author.mention}.',
                 f'Yes indeed, {ctx.message.author.mention}.',
                 f'Absolutely not, {ctx.message.author.mention}.']
    await ctx.send(f'{random.choice(responses)}')

@client.command()
@commands.has_guild_permissions(manage_messages=True)
async def say(ctx, *args):
    await ctx.send(' '.join(ctx.message.content.split()[1:]))
    await ctx.message.delete()

@say.error
async def say_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f":x:  You don't have permission to use that, {ctx.author.mention}.")

@client.command()
@commands.is_owner()
async def dm(ctx, member : discord.User, *, message):
    person = ctx.author.id
    await member.send(message)
    await ctx.send(f'DM sent to {member}.')
    return
    print(f"The command 'DM' was used in the server: {ctx.guild}")

@dm.error
async def dm_error(ctx, error):
    if isinstance(error, commands.NotOwner):
        await ctx.send("Only the owner of this bot can use this command.")

@client.command()
async def run(ctx, *, commandtorun):
    person = ctx.author.id
    if person == int("789545965912457217"):
        commandoutput = subprocess.getoutput(commandtorun)
        if commandoutput == "":
            await ctx.send("Command has been ran. :white_check_mark:")
            return
        await ctx.send(f"```{commandoutput}```")
    if person != int(""):
        await ctx.send("Sorry, but this command is restricted to the owner of this bot and nobody else.")
        print(f"The command 'run' was used in the server: {ctx.guild}")

client.run('TOKEN')

这是我的代码。任何和所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

on_message 方法中,else 子句中没有 breakreturn

@client.event
async def on_message(message):    
    for bad_word in bad_words:
        if bad_word in message.content.lower().split(" "):
            ...
            break
        else:
            await client.process_commands(message)
            # no break or return statement here

这意味着只要消息不包含 await client.process_commands(message) 中的每个 bad_word,机器人就会运行 bad_words。要解决此问题,请将 break 替换为 return 并将 await client.process_commands(message) 放在 for 循环之后。