Home > Software engineering >  Discord Bot Error trying to send to a unique channel ID
Discord Bot Error trying to send to a unique channel ID

Time:12-05

when I am trying to send a message to a channel it won't work. Anyone knows why?

This here is the command I am using. This is just the code block of the not working section.

@bot.command(pass_context=True)
    async def test2(ctx):
    await ctx.message.delete()
    print("The Test is being started")
    Channel = config['bot']['id1']
    await Channel.send("test2")

And in My Config file, I have this

[bot]
id1= 916845047CENSORED

And when I try to run it I get this error:

The test is being started
Ignoring exception in command test2:
Traceback (most recent call last):
  File "C:\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/jp/Desktop/DISCORD BOT/bot.py", line 224, in test2
    await Channel.send("test2")
AttributeError: 'str' object has no attribute 'send'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'send'

If anyone knows how to fix this I would thank you very much

CodePudding user response:

Look at line 85 to find the line throwing the error. It's saying that the Channel object taken from config['bot']['id1'] is of type str. You are then trying to invoke the method .send() on a str type, which it does not have.

...
Channel = config['bot']['id1']
await Channel.send("test2")

CodePudding user response:

With discord.py, channel objects are not just integers. Instead, you have to fetch the channel, either from a guild after fetching the guild with its id, or fetching the channel straight away. Here are some ways to do this:

Channel_Id = config['bot']['id1']

# Method 1: Fetching channel straight away
Channel = bot.get_channel(Channel_id)

# Method 2: Fetching channel from guild
Guild_Id = config['bot']['GuildId'] # of course you may need to add a new config
Guild = bot.get_guild(Guild_Id)
Channel = Guild.get_channel(Channel_Id)

await Channel.send("Test")

Other helpful links:

Please note: When searching for this answer, it is recommended not to use bot.fetch_channel as this is an API call. The above methods are recommended for general use.

  • Related