简单的bot命令在discord.py中不起作用

时间:2020-06-23 11:29:04

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

我想知道管理员想在哪些文本通道中启用我的漫游器功能。但是在这种情况下,我的代码无法正常工作。

主要思想是,当管理员在文本聊天中输入!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()

1 个答案:

答案 0 :(得分:1)

channel变量已在程序中初始化,因此每次您重新启动bot时,它将被清空。解决问题的一种方法是将它们存储在文件中。最简单的方法是使用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文件:
[]