harvs
harvs

Reputation: 23

How to get channel of command used | discord.py

If someone send a command in lets say the general channel, how would i get that channel. Like ctx.author.voice.channel, is there a way to use ctx.author to get the text channel?

Upvotes: 1

Views: 4086

Answers (2)

unofficialdxnny
unofficialdxnny

Reputation: 311

Well you cant use ctx.author or user as they are not channel specific.

Here is a simple snippet you can use.


@client.command()
async def test(ctx):
    channel = ctx.channel
    await ctx.channel.send('test')

Upvotes: 0

Trevor
Trevor

Reputation: 595

You can't use ctx.author to get the channel, because discord.Members and discord.Users are not channel specific. You can however, use ctx.channel to get the channel the command was used in.

You can use:

@bot.command()
async def get_this_channel(ctx):
    channel = ctx.channel
    # .. do things

With that being said, this is separate from Views with discord.py 2.0, which allow for 1st party support of buttons and drop down menus.

Please do not use third party libs for buttons when they're already worked into Discord.py 2.0... they're bad.

Check out this example of a simple button using discord.py 2.0

import discord
from discord.ext import commands

class ThisUI(discord.ui.View):
    def __init__(self):
        super().__init__()
        
    @discord.ui.button(label='Test button!')
    async def test_button(self, button, interaction):
        channel = interaction.channel
        
        if channel is not None:
            await channel.send('Hello from a button!')

class Commands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.command()
    async def testbuttons(self, ctx):
        return await ctx.send("Hey now!", view=ThisUI())

Please view both the documentation for this, and some examples from the repository

Upvotes: 1

Related Questions