Get message author in Discord.py

Viewed 25210

I am trying to make a fun bot for just me and my friends. I want to have a command that says what the authors username is, with or without the tag. I tried looking up how to do this, but none worked with the way my code is currently set up.

import discord
client = discord.Client()

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('$WhoAmI'):
        ##gets author.
        await message.channel.send('You are', username)

client.run('token')

I hope this makes sense, all of the code i have seen is using the ctx or @client.command

3 Answers

The following works on discord.py v1.3.3

message.channel.send isn't like print, it doesn't accept multiple arguments and create a string from it. Use str.format to create one string and send that back to the channel.

import discord

client = discord.Client()

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('$WhoAmI'):
        await message.channel.send('You are {}'.format(message.author.name))

client.run('token')

Or you can just:

import discord
from discord import commands

client = commands.Bot(case_insensitive=True, command_prefix='$')

@client.command()
async def whoAmI(ctx):
   await ctx.send(f'You are {ctx.message.author}')

If you want to ping the user:

import discord
client = discord.Client()

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('$WhoAmI'):
        await message.channel.send('You are', message.author.mention)

client.run('token')
Related