Home > front end >  discord.py @bot.command() not working in the channels but DM OK
discord.py @bot.command() not working in the channels but DM OK

Time:12-17

I wrote a bot using discord.py. The problem is it responds to my DM, but not to my message in channels. Could anyone help with it?

import discord
import requests
import urllib.request
import os
from io import BytesIO
from PIL import Image 
from discord.ext import commands

bot = commands.Bot(command_prefix='!')
@bot.event 
async def on_ready(): 
    print('We have logged in as {0.user}'.format(bot))

@bot.event 
async def on_message(message): 
    await bot.process_commands(message)

@bot.command() 
async def bothello(ctx): 
    print(ctx.channel) 
    if isinstance(ctx.channel, discord.DMChannel): 
        await ctx.send(f'DM') 
    elif isinstance(ctx.channel, discord.TextChannel): 
        print(ctx.channel.name) 
        await ctx.send(f'channel: {ctx.channel.name}') 
    else: 
        print("no way") 
    print('hello')

bot.run('MY_BOT_TOKEN')

I tried to modify the permisson but to no avail.

CodePudding user response:

I will guess that you're using discord.py library and not its forks, since it's in your question tags.

So, first, it doesn't look like you're using discord.py 2.0 since you're not getting an exception about not passing the intents keyword argument. Make sure that you have an up-to-date discord.py by trying to update it using: python -m pip install -U discord.py

Second, the reason your bot isn't responding to commands in the server is because you don't have the message_content privileged intent that was new in 2.0; since it doesn't have the intent, it cannot access the content of the message that was sent in the server, so you need to enable it in the dev portal and in the code. Example (code):

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(..., intents=intents)

You may want to look at discord.py's guide on how to enable the intent in the dev portal here.

  • Related