Search code examples
pythondiscorddiscord.py

Discord.py bot not sending messages in a discord server but sends messages in DM's


I have a discord.py bot that when the command is sent through DM, it works. When the command is ran through a server, nothing happens. There is no errors or tracebacks. Here is my code so far.

import discord
from discord.ext import commands

bot = discord.Bot()

TOKEN = "MyToken"

bot = commands.Bot(command_prefix="$")

@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

bot.run(TOKEN)

I don't know whats happening. I gave it the right permissions but it still wont do anything.


Solution

  • For this, I believe you have fiddled it up by using the bot = variable twice, in two different ways. The way I would do it is as following:

    First, import our libraries and define the token:

    import discord
    from discord.ext import commands
    
    TOKEN = "MyToken"
    

    Next, we need to set up the bot variable, as so:

    bot = commands.Bot(command_prefix='$', intents=discord.Intents.all()) # I usually add all intents, you can use discord.Intents.default if you like.
    

    I add intents because Discord sometimes gets angry if you do not, so I like to make it a just in case backup.

    Now, we create the command:

    @bot.command()
    async def test(ctx, arg):
        await ctx.send(arg)
    

    And lucky last, log into our bot:

    bot.run(TOKEN)
    

    Prior to our command, you can enter an on_ready function to verify the bot has logged in correctly:

    @bot.event
    async def on_ready():
        print(f"{bot.user} logged in successfully.")