Skip to content
Advertisement

Discord BOT with Python, How to make it reply in the channel we send the command (Done)

Done! Thanks to anyone who helped me out:) Still maybe you have better answers, so, feel free to answer!

I know, this may look like a stupid question, but if you consider that I’m a beginner in making bots for Discord in Python beyond all my other Python knowledge and Stack Overflow being probably a place just for that, I hope it wouldn’t. (I’m so new that I literally woke everyone in the home up by my happiness when I saw my bot turned online lol)

As I saw in other posts, tutorial, etc.; (don’t mind the usage of , and ; it could be wrong) we have to specify the ID of the channel, so how can we just reply in the channel the user has sent the command in? Maybe getting the ID of the current channel with some type of a command? I don’t know.

import discord

TOKEN = 'XXXXX'

client = discord.Client()

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

    if message.content.startswith('!hello'):
        msg = 'Hi {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)

(Since I’m lazy regenerating tokens, i made it xxxxx in this example but don’t worry i put it in the normal code.)

As I saw, there is no same question even though there are similar ones (i couldnt see an answer or a question definitely because everybody knows how to do that)

The problem is in the send_message part. It gives an error.

Advertisement

Answer

You just have to get the channel object and send a message to it using message.channel.send() and not client.send_message()

if message.content.startswith('!hello'):
    msg = 'Hi {0.author.mention}'.format(message)
    await message.channel.send(msg)

In the future you may wanna try something like this or maybe come across it by any reason:

from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.command()
#This is defining a '!hello' command
async def hello(ctx):
    #In this case you have to use the ctx to send the message
    #Good to remember that ctx is NOT a parameter wich the user will give
    msg = f'Hi {ctx.author.mention}'
    await ctx.send(msg)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement