I am currently trying to create a discord bot that, when someone says a command it says what server and what channel they are in. I was able to do this in the past, however in the past I was using on_message(message) and if message.content.startswith('$hello'). I recently started using @bot.command and I'm still trying to get used to it. I tried using message.guild.name and message.channel.mention but I get an error message. Undefined variable 'message' I assume this is because with my old setup, in the on_message(message) I define message, however with my current code it doesn't seem to work.
import discord
import asyncio
from discord.ext import commands
botToken = token
bot = commands.Bot(command_prefix = '#')
client = discord.Client()
@bot.event
async def on_ready(): print('Bot is online and ready.')
@bot.command()
async def whereAmI(ctx, *, messageContents): link = await ctx.channel.create_invite(max_age = 300) message = 'You are in {message.guild.name} in the {message.channel.mention} channel with an invite link of ' + link await ctx.message.author.send(message)
bot.run(botToken)And I am aware that it might DM the person, however I'm currently working on just my test bot before I bring the command over to my main one. If you have any better ideas please let me know. And the reason why I have the variable there is because I am planning on including the variables in the final product.
If anything doesn't make sense, let me know and I will edit it to hopefully make it more clear and give more context if needed.
2 Answers
To get the message object, you need to use the passed-in "context" (ctx). So it would be ctx.message.guild.name and ctx.message.channel.mention. Docs on Context
On another note, Bot is a subclass of Client. So whatever Client can do, Bot can do too. You don't need a Client and Bot, just the Bot. Docs on Bot subclass
2This is an example of how it should be.
@bot.command()
async def whereAmI(ctx, *, messageContents): link = await ctx.channel.create_invite(max_age = 300) message = f'You are in {ctx.message.guild.name} in the {ctx.message.channel.mention} channel with an invite link of ' + link await ctx.message.author.send(message)Have a good day!
0