【问题标题】:Simple bot command is not working in discord.py简单的 bot 命令在 discord.py 中不起作用
【发布时间】:2020-10-13 10:46:48
【问题描述】:

我想知道管理员想要在哪些文本频道中启用我的机器人功能。但在这种情况下,我的代码不起作用。

主要想法是当管理员在文本聊天中输入!enable 时,机器人会对其做出反应并将文本聊天 id、公会 id(ctx.channel.id) 添加到列表中,然后机器人在与bot has been enabled 的聊天中做出响应。

此命令不起作用的代码:

channel = []
@bot.command()
async def enable(ctx):
    global channel
    print("Debug")
    await ctx.send('Restriction bot has been enabled for this text channel.')
    channel.append(ctx.channel.id)

完整的机器人代码:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user.name}.')


channel = []
@bot.command()
async def enable(ctx):
    global channel
    print("Debug")
    await ctx.send('Restriction bot has been enabled for this text channel.')
    channel.append(ctx.channel.id)


@bot.event
async def on_message(ctx):
    if ctx.author == bot.user:
        return
    #if ctx.channel.id != [for channnels in channel]:
    #    return
    if ctx.attachments[0].height:
        await ctx.author.send('Your media file is restricted!')
        await ctx.delete()

【问题讨论】:

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


    【解决方案1】:

    channel 变量已在您的程序中初始化,因此每次您重新启动机器人时,它都会被清空。解决问题的一种方法是将它们存储在文件中。最简单的方法是使用 json 库。您需要创建一个channels.json 文件。

    • 代码:
    from json import loads, dumps
    
    def get_data():
        with open('channels.json', 'r') as file:
            return loads(file.read())
    
    def set_data(chan):
        with open('channels.json', 'w') as file:
            file.write(dumps(chan, indent=2))
    
    @bot.command()
    async def enable(ctx):
        channels = get_data()
        channels.append(ctx.channel.id)
        set_data(channels)
        await ctx.send('Restriction bot has been enabled for this text channel.')
    
    • channels.json 文件:
    []
    

    【讨论】:

    • 我将您的代码记录到我的bot.py 中并创建了新的members.json 文件(但您输入的是创建一个channels.json,可能是它的拼写错误idk),我没有得到任何结果。我认为主要错误在@bot.command()
    • 这个命令唯一要做的就是添加每个写了 !enable 的通道。我忘了告诉你,你需要在 channels.json 中添加一个空列表
    • 非常感谢!我想我需要修复我的@bot.command() 因为当我输入 !enable 时聊天没有效果:D
    • 您在输入命令时是否有任何错误信息?
    • 只是因为我很笨xD我忘了替换set_data函数中的第二个members.json。如果你现在复制粘贴代码,它应该可以工作(我试过只是为了确保)
    猜你喜欢
    • 2020-08-16
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多