Switchback
Switchback

Reputation: 97

Simple bot command is not working in discord.py

I want to know in which text channels admin want to enable my bot functions. But in this case my code is not working.

The main idea was when admin typing !enable in text-chat, bot reacts to it and add text-chat id, guild id(ctx.channel.id) to the list, then bot responds in chat with bot has been enabled.

code where this command is not working:

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)

full bot code:

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()

Upvotes: 0

Views: 892

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

The channel variable is initialized in your program so each time you will restart your bot, it will be emptied. One way you can solve your problem is by storing them in a file. The easiest way to do it would be to use the json library. You'll need to create a channels.json file.

  • The code :
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.')
  • The channels.json file :
[]

Upvotes: 1

Related Questions