How to make a bot join a channel and respond in chat discord.py

Tags: , ,



I just started learning to code very recently in order to make a discord bot in python. I have used both pieces of code separately and they have worked, but when trying to use them together only the messages work, and the bot will not join the voice channel.

No errors come up when I type the join command.

However, I can’t seem to find the error. If someone could look over my code and find where I’m going wrong, it would be greatly appreciated, thanks.

@client.command
async def join(ctx):
  if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    await channel.connect()
  else:
    await ctx.send("I am terribly sorry, but I cannot join you as you are not in a voice channel.")

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  msg = message.content
  
  if any(word in msg for word in stimulus_words):
    await message.channel.send(random.choice(stimulus))

Answer

First of all, your code looks pretty good for someone new to Discord.py

The problem comes from the fact that your async def join(ctx): is not registered as a command by discord. This can be done by adding @client.command() on top of your function. This way it will be recognized and called with the context when someone uses $join ($ = a prefix that you chose for your bot). You can find more information here

Also, I would recommend looking into Cogs that are a good way to organise your code

PRE-EDIT : I see you edited your code to add the decorator on top of your function, however you are missing the ( ) so this is why it is not working in my opinion



Source: stackoverflow