Discord.py Getting channel name and server name returns an error message
Solution 1
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
Solution 2
This 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!
EchoTheAlpha
I am the worse coder ever. I basically only know Python. So i will ask a lot of python questions and not understand nearly everything that im being told, but if it works i will try to figure out why it does work.
Updated on June 05, 2022Comments
-
EchoTheAlpha about 2 years
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)
andif message.content.startswith('$hello')
. I recently started using@bot.command
and I'm still trying to get used to it. I tried usingmessage.guild.name
andmessage.channel.mention
but I get an error message.Undefined variable 'message'
I assume this is because with my old setup, in theon_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.
-
EchoTheAlpha about 4 yearsWith the current
async def whereAmI(ctx, *, messageContents):
command that i currently have, how would i tell it to use the passed-in context? Would i replace@bot.command
with@bot.command(pass_context=True)
? -
Kelo about 4 yearsYou are already passing in the context. It's the ctx parameter. Context comes along with the command automatically. So no need for the
pass_context
bit :) Docs on Commands