#Basic Pycord Help (Quick Questions Only)

1 messages · Page 57 of 1

grizzled sentinel
#

@fervent cradle ^

proud mason
#

Oops lol

fervent cradle
fervent cradle
grizzled sentinel
#

.rtfm discord.ui.select

fervent cradle
#

alr thanks! sorry once again

grizzled sentinel
#

as a decorator instead of sub classing the select. It is still best practice to subclass the view though.

grizzled sentinel
fervent cradle
limber urchin
#

yes

fervent cradle
#

gotcha

high jay
#

why is suraj not printed?

limber urchin
#

Because you're breaking the loop when you hit Taruna

#

And you should probably go to a different server, this is not a place to be learning basic Python.

restive juniper
#

how do i disable slash commands in dms?

#

please @ me if you respond

proud pagoda
restive juniper
#

alright thank you

proud pagoda
#

Np

restive juniper
#

is there any better way to get everyone in a server that has a specific role instead of looping through everyone and checking if they have the role?

#

@proud pagoda

silver moat
fervent cradle
#

Does anyone have a example of discord.ui.select where the options change based on the input of the user?

full basin
full basin
#

And what would the user choose/how would it work exactly

silver moat
fervent cradle
#

Right I was thinking about that, might be the best approach

#

Yeah that is the best option

#

I'll do just that, thanks

silver moat
#

yw

fervent cradle
#

What's the limit on how many options you can have, 25?

full basin
#

Yes

fervent cradle
#

Thanks

limber urchin
#

Just saying you are getting an error isn't helpful. Show your code and your pip list

loud sail
#

Hey, can someone help me with this: I'm not getting an error in the console & nothing is noticeable when debugging either. The problem is that when I run the slash command in Discord, the bot doesn't respond and Discord returns "The application didn't respond".

silver moat
limber urchin
#

if activities is a useless check because it's always going to be defined

silver moat
#

try deferring

austere bobcat
#

please help guys pycord no work with the onmessage
@client.event
async def on_message(message):

silver moat
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

silver moat
#

?tag message-content

loud sail
obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

drowsy oriole
#

does django or flask makes sense if you work with vuejs3 frontend?
Just as an api server i think?

limber urchin
#

Why wouldn't it?

proud mason
#

dont fetch user. you should already have everything

#

defer the response at the first line of the callback

flat kite
proud mason
#

fastapi is cool too pepehmm

silver moat
#

not for static web pages

flat kite
loud sail
drowsy oriole
#

fastapi looks very good

limber urchin
#

Django is also very overkill if you only want a backend to set up an API

pearl juniper
#

What's the difference between discord.Bot() and commands.Bot?

silver moat
#

?tag inheritance

obtuse juncoBOT
#

dynoError No tag inheritance found.

silver moat
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
pearl juniper
silver moat
#

ig

sick quest
#

is there a way to make it so when a bot sends a modal there is already text in the input field that the user can edit?

limber urchin
#

Set the value attribute of the TextInput. The docs literally tell you this

eternal wing
#

I started getting this error when i launch my bot and it doesn't update any commands anymore...

venv\lib\site-packages\discord\http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options

I thought it may be of discord options but i haven't changed those, yet it suddenly started showing it.

silver moat
#

maybe you updated the code, but didn't run the bot

eternal wing
#

I added one command. Tried removing it and it still throws the error... I tried looking if i have the required options behind non-required (as the error says), but to no avail, where multiple options are either all are non-required or all are required.

#

Just tried removing the command again.. now it doesn't throw an error... ahh to find the problem now

#

Solved! Just added "default" value to the option that didn't have it and no more error! Really strange tbh

zinc cloak
#

How does one get the item selected from a selection callback?

young bone
zinc cloak
#

Wait I need to clarify 1 min...

errant craneBOT
#

Here's the dropdown example.

zinc cloak
#

Yeah I looked at that...

young bone
fervent cradle
#

how can i edit a response

young bone
fervent cradle
#

yeah

#

it keeps telling me i cant'

young bone
#

ctx.edit()

fervent cradle
#

wait

#

omfg

#

im dumb

#

💀

zinc cloak
# young bone

Thanks! I got it. Just needed to create a separate class instead of the weird workaround I was doing before.

young bone
fervent cradle
#
@bot.command()
async def ping(ctx):
    await ctx.respond("Pinging...")
    start = time.time()
    result = requests.get("https://discord.com/api")
    end = time.time()
    elapsed_time = (end - start) * 1000
    await ctx.edit(f"Pong! ({elapsed_time:.2f} ms)")```
#

am i doing something wrong

#
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given```
young bone
#

content=""

fervent cradle
#

💀

young bone
#

xd

#

also dont use requests

fervent cradle
#

is there a better way to do it

young bone
#

aiohttp

fervent cradle
#

thx

zinc cloak
#

In components.0.components.0.options: Must be between 1 and 25 in length.
I seem to be getting this weird error.

Code:

            elif self.selection == 'voice_channel':
                for channel in guild.voice_channels:
                    if len(options_list) >= 20:
                        selects.append(Select(options=options_list))
                        options_list = []
                    else:
                        options_list.append(discord.SelectOption(label=channel.name))
                selects.append(baseSelect(options=options_list))
                for select in selects:
                    view.add_item(select)
                    print(select)```
This same code works for text channels, but for voice channels it gives the error.
I'm not sure why.
#

When I print the selects it gives me a baseSelect with options which is normal

#

What does this error even mean

limber urchin
#

It means you're adding too many options to the select, or none at all

zinc cloak
#

Ok I'll try some things. Thanks!

zinc cloak
# limber urchin It means you're adding too many options to the select, or none at all

When printing the children of view I get:

[<baseSelect type=<ComponentType.string_select: 3> placeholder=None min_values=1 max_values=1 options=[<SelectOption label='annoucements' value='annoucements' description=None emoji=None default=False>, <SelectOption label='rules' value='rules' description=None emoji=None default=False>, <SelectOption label='about' value='about' description=None emoji=None default=False>, <SelectOption label='changelog' value='changelog' description=None emoji=None default=False>, <SelectOption label='reaction-roles' value='reaction-roles' description=None emoji=None default=False>, <SelectOption label='general' value='general' description=None emoji=None default=False>, ... (more select options afterward)```
#

OH WAIT

#

I'M BIG DUMB

#

I don't have any voice channels in the server...

#

I'm so sorry...

#

tysm btw

fervent cradle
#
@bot.event
async def on_member_join(member):
    global welcoming
    global checking_age
    welcome_channel = bot.get_channel(1073385967722954782)
    if checking_age:
        if (member.created_at - member.joined_at).total_seconds() / (3600 * 24) < 10:
            await member.kick(reason="Account age is under 10 days.")
    if welcoming:
        await welcome_channel.send(f"Hi {member.mention}! Welcome to the server!")
    async for entry in welcome_channel.history(limit=10):
        if (member.joined_at - entry.created_at).total_seconds() <= 5:
            welcoming = False
            checking_age = True
            start
            await welcome_channel.send("WARNING: RAID DETECTED | DISABLING WELCOME MESSAGES AND ENABLING AGE CHECKS | @languid wave @Literally An Axolotl#0001")
            return```

am i doing something wrong here cuz this is how i did it in discord.py when it was still a thing
limber urchin
#

?tag idw

obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

fervent cradle
#

bro 💀

#

theres no error it just dosent detect joins

limber urchin
#

So the issue is that the event isn't firing?

fervent cradle
#

yeah

limber urchin
#

Then specify that, we can't guess what your issue is.

#

Do you have member intents?

fervent cradle
#

yuh

#
intents = discord.Intents.all()

bot = discord.Bot(intents=intents)```
#

thats correct right

#

or am i dumb

limber urchin
#

It also has to be enabled in your developer portal

fervent cradle
#

they are

#

@limber urchinnvm they werent enabled in the portal

#

but it spams messages in the chat when a raid is detected

#

it shouldnt do that, do u know why

limber urchin
#

Because your code makes it send a message on every join?

fervent cradle
#

oh

#

wait

#

fuck mb

#

💀

fervent cradle
#

whats the method for ctx.author.avatar_url in pycord

#

cuz that shit aint working

limber urchin
#

it's not a method, it's an attribute

fervent cradle
#

same thing

limber urchin
#

Not at all, but yeah

#

.rtfm User.avatar.url

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

limber urchin
#

.rtfm User.avatar

winter condorBOT
limber urchin
#

.rtfm Asset.url

winter condorBOT
fervent cradle
#

so do i just use the avatar object

#

im not the most expirienced 💀

limber urchin
#

Take a look at the docs and you'll know

fervent cradle
#

so i use discord.User.avatar.url???

#

@limber urchin

#

sorry im stupid 💀

limber urchin
#

.tias

winter condorBOT
fervent cradle
#

gay

limber urchin
#

?

frank shale
#

Lol #ignore

uneven thorn
#

anybody know how to add execption if bot has no perm to add roles

proud mason
#

Do you mean raise exception ?

limber urchin
#

Yeah, what do you mean by "add" exception?

uneven thorn
#

like to catch on execpt block

#

except

#

sorry eng not my main lang

limber urchin
#

.rtfm Forbidden

winter condorBOT
uneven thorn
#

it wont work for me

#

lemme try agan

#

with the help of github copilot

limber urchin
#

Maybe it's easier if your write your own code instead of relying on copilot

uneven thorn
#

yeah i did

#

like that?

limber urchin
#

Well I can't see the rest of your code so I don't know. Try it and see

uneven thorn
#

imma test it brb

#
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
#

now that error appear

#

lemme go look on that on the doc

#

oh wait i think i know why

#

since i added the response before i actually add the role

#

works now thx

errant craneBOT
#

Here's the buttons example.

boreal abyss
#

i want a buttons example...

errant craneBOT
#

Here's the @everyone example.

tardy dirge
#

no i need how to make the bot not ping

boreal abyss
#

how to make the button clickable only by the uh owner who ran the cmd

fervent cradle
#

.rtfm interaction_check

winter condorBOT
fervent cradle
# winter condor

@boreal abyss the second one, discord.ui.View.interaction_check

#

You add it to your view, and in the interaction_check method you check if the interaction.user.id is the same as the owner's ID. return a True if it is, the button's callback will process, otherwise it does nothing.

fervent cradle
boreal abyss
errant craneBOT
#

Here's the interaction example.

proud mason
#

.rtfm allowed

boreal abyss
#

its not helping

#

how can i add that in my "Class"

#

why do i await it?

#

why IS THERE no code example just like what djs do

#

dayum

proud mason
#

Override that method

#

It should return a bool

glossy sand
#

Hey, so I have a view that I need to make persistent but to instantiate an object of this class I need to pass in a bunch of parameters, how would you pass in the parameters in

bot.add_view(MyView())

For example I need to pass in a user object to MyView which will be used to check if the user exists in my db, I can do this fine when I'm sending the view from a command because I can pass in ctx.user but what do I pass for user in bot.add_view(MyView()) ?

proud mason
#

You can also store user id and use bot.get_user to get the user object at runtime

glossy sand
#

ah that makes sense, also sounds like my work just increased lol, thanks though

proud mason
#

Lol good features aren't always easy

rocky sparrow
#
    a = int(x)
    print(a)
    
    channel = await ctx.guild.fetch_channel(a)```
 x returns a value of numbers  but when i put in channel var it says unkown  var
proud mason
rocky sparrow
proud mason
# rocky sparrow

Well that channel is not found in the server. Are you sure the id is correct?

covert kayak
#

Is it possible to have button interaction as a boolean? For example, if click button A then execute command(x), if click button B then execute command(y) lol

grizzled sentinel
errant craneBOT
#

Here's the confirm example.

grizzled sentinel
covert kayak
#

Thank you rooAww

soft girder
#

Is it possible to write a script or code that will restart the chatbot in case of an error.

#

I I tried to write (it works badly), but I would like to learn from people who know programming better.

#

I would be grateful to anyone who can help.

#

@bot.event
async def on_error(event, *args, **kwargs):
await bot.logout()
await bot.close()
await bot.connect()

#

It can help 🤔🤔

obtuse juncoBOT
#

Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().

Do use:

  • run your bot in a process manager such as:
    • systemd
    • openrc (gentoo, devuan)
    • runit (void linux)
    • supervisord
    • upstart (old ubuntu)
    • docker
  • manually reboot it

Do not use:

  • a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
  • subprocess.call (you will eat your memory up by not letting your old processes die)
  • os.exec*
versed fern
#

Is there a better way of sending/editing messages than using modals? (Using application commands and without having the msg content intent)

proud mason
#

Are you getting user input?

fervent cradle
#

How to set a none status like the following?

full basin
#

Most likely it's a bot that only uses HTTP requests

#

So that's why it doesn't have a status

still helm
#

I am sending a message through a webhook to a thread, all works fine. But i don´t know why there is :

"Ursprüngliche Nachricht wurde gelöscht" - Original message has been deleted

rocky sparrow
#
    a = int(x)
    print(a)
    
    channel = await ctx.guild.fetch_channel(a)```
 x returns a value of numbers  but when i put in channel var it says unkown  var
versed fern
# proud mason Are you getting user input?

Yup. It’s to allow the admins to send and edit custom messages (multi-line including formatting). Currently using modals which works fine for sending messages, but is a little inconvenient when it comes to editing if you only want to edit a small part of the message while keeping the rest exactly the same

proud mason
#

also, which python version and show pip list

proud mason
#

why is it inconvenient to edit messages?

#

if it is a button click to edit msg, pass interaction.message which creating the modal instance, and store it on a self variable in the modal

#

use that to edit in the modal callback

versed fern
#

Cause you can’t just backspace 5 characters and keep the rest the same

#

Ig I’ll just add a copy raw text command

#

Just thought there might be a cleaner way

proud mason
versed fern
#

I’ll interpret this as "I understand what you’re trying to archive, but unfortunately don’t know another way"

proud mason
#

what did you mean by "Cause you can’t just backspace 5 characters and keep the rest the same"

versed fern
#

Let’s say I send this message.

Edit: Now I can add those words without having to reformat/type the words prior

proud mason
versed fern
#

Kinda like editing your own message, I want the initial message to be already typed, allowing the user to add or edit smaller portions without having to manually copy or rewrite the initial message

proud mason
#

smth like content = message.content + "\n\n" + input_text.value

versed fern
#

I gotta exit the train now and than walk home, I’ll check in here later tho

proud mason
#

lol alr

proud mason
# rocky sparrow Wdym

channel = await ctx.guild.fetch_channel(12345) where 12345 is an actual channel id you confirmed is in the server

versed fern
#

Is there anyway to already have some typed out text (in my case the raw initial message content) pre entered to a modal field? This would allow the users to edit the text similarly to editing their own messages

grizzled sentinel
versed fern
#

That's exactly what i was looking for, thank ya

pearl juniper
#

How to place some embed field like this?

#

Because i need to add everytime blank field between all inline field

#

All Field are inline

young bone
#

embed.add_field?

#

Or the description

#

?tag embed

obtuse juncoBOT
#

dynoError No tag embed found.

fallen cove
#

is there a way to show a list of scheduled events in a slash command option(bit like how to get a list of channels)?

full basin
#

Do we have docs about role connections?

fervent cradle
#

what might be the issue of bot restarting itself on linux vps but not on my windows pc?

full basin
#

on_ready can fire multiple times while the bot is running

fervent cradle
#

oooh thanks :D

sick oriole
#
import B
import os
from discord.ext import commands
bot = discord.Bot()```
I am not sure why my bot isn't connecting to discord.
#

It keeps saying module discord has no attribute 'bot'

full basin
#

Most likely you have conflicting libraries

devout anvil
#

@sick oriole

silver moat
devout anvil
#

Wait what

silver moat
#

I'm not saying that commands.Bot is wrong. I'm saying discord.Bot exists

silver moat
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
devout anvil
#

I think we need the full code to figure out the problem properly

silver moat
#

It would be a dependency/package issue

full basin
#

ping

limber urchin
gilded niche
#

When using a select menu with user_select on mobile it only shows a small list of names. Is there any way to fix this?

dreamy mauve
#

how to make these type of points in an embed?

fervent cradle
#

hello
So ">" and a space in front of your text

so it's > hello

#

is it normal for my bot to not go online out of nowhere?

amber shale
#

hey, i have a backend for my website using django, and how to things like kicking a person using website?

#

backend sends request to bot?

fervent cradle
#

like

#

it wont go online without any changes whatsoever

#

it worked completely fine some days ago

proud mason
proud mason
#

See latest msg in #discord-api-updates

fervent cradle
#

hmm ill try again in a bunch of days, if not i'll come back ig

#

i did

proud mason
#

Also, make sure to update to latest pycord version

fervent cradle
#

i did too 😉

proud mason
#

Nice

fervent cradle
#

tried everything i could

proud mason
#

What about a different bot token?

fervent cradle
#

tried with a completely different bot lmfao

#

and new token ofc

proud mason
#

Did that work?

fervent cradle
#

and i get no errors aswell

proud mason
#

Hmm

fervent cradle
#

no, i tried running on cloud but same thing

proud mason
#

What happens when you run just a basic bot

fervent cradle
#

let me do so

errant craneBOT
#

Here's the basic bot example.

proud mason
#

Like that

fervent cradle
#

let me run it

#

That goes online 😭

#

then it has to be somewhere in my code

#

let me check it again

proud mason
#

Rip

#

If you need help finding the issue, you can share your code here

fervent cradle
#

Is there any way to show the attachment from discord.Option(discord.Attachment) in an embed image?

fervent cradle
#

what is it?

young bone
#

what is it returning?

fervent cradle
#

How do i edit the response to a slash command?

winter condorBOT
proud mason
#

That, along with

#

.localfile

#

?tag localfile

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
proud mason
#

(ofc without the 1st line)

young bone
real frost
#

heyyo

#

Can anybody help me?

#

In modal dialog button submit don't working

young bone
obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

real frost
#

Ok, i send Modal through the button like this

await interaction.response.send_modal(Reason(timeout=60, title='Введите причину', id=id, closer=interaction))
class Reason(discord.ui.Modal):
    def __init__(self, id,closer, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.closer = closer
        self.id = id
        self.add_item(discord.ui.InputText(label="Укажите причину закрытия", placeholder='Bla-Bla-Bla', value='Не указана', style=InputTextStyle.long))
    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message(embed=Embed(description=f'Вы успешно закрыли тикет с причиной `{self.children[0].value}`!'), ephemeral=True)
        member = await interaction.guild.fetch_member(self.id)
        await member.send(embed=Embed(description=f"{'❎ Ваш тикет был закрыт администратором!' if interaction.user.id != member.id else '❎ Вы закрыли свой тикет!'}\n{f'🟨 Администратор: {interaction.user}' if interaction.user.id != member.id else f'🟨 Администратор: {interaction.user}'}\n{f'✅ Комментарий: {self.children[0].value}' if interaction.user.id != member.id else f'✅ Вааш комментарий: {self.children[0].value}'}" ))
    async def on_timeout(self):
        member = await self.closer.guild.fetch_member(self.closer.user.id)
        await member.send(embed=Embed(description=f"{'❎ Ваш тикет был закрыт **администратором**!' if self.closer.user.id != member.id else '❎ **Вы** закрыли свой тикет!'}\n{f'🟨 Администратор: {self.closer.user}' if self.closer.user.id != member.id else f'🟨 Администратор: {self.closer.user}'}\n✅ Комментарий: **Не был указан**" ))

It just don't working

#

I figured it out

#

im so dumb

soft girder
#
class NS(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    game = SlashCommandGroup("newstate", "Various greeting from cogs!")

    
    class Pass(discord.ui.Modal):
        def __init__(self, *args, **kwargs) -> None:
            super().__init__(*args, **kwargs)

            self.add_item(discord.ui.InputText(label="LOBBY name:",min_length=4,max_length=25,placeholder="Enter the title." ,style=discord.InputTextStyle.long))
            self.add_item(discord.ui.InputText(label="Time:",max_length=40,placeholder="Start time." ,required=False, style=discord.InputTextStyle.multiline))
            self.add_item(discord.ui.InputText(label="Password:",max_length=6,placeholder="Enter password." ,style=discord.InputTextStyle.multiline))
            self.add_item(discord.ui.InputText(label="Map/Perspective:",max_length=400,placeholder="Map/Perspective", style=discord.InputTextStyle.long))
            self.add_item(discord.ui.InputText(label="Additionally:",max_length=3000,placeholder="Enter ",required=False, style=discord.InputTextStyle.long))
        

        async def callback(self, interaction: discord.Interaction):
            embed = discord.Embed(title=f"PASSWORD MENU" , description=f"**LOBBY:** **{self.children[0].value}** {self.children[1].value}\n\n**PASSWORD:** **{self.children[2].value}**\n\n**MAP|FPP/TPP:** {self.children[3].value}\n\n**ADDITIONALLY:** {self.children[4].value}" ,colour=discord.Colour.random())
            await interaction.response.send_message(embeds=[embed])
      
    @commands.has_permissions(administrator =True)
    @game.command(name='password', description='Write form the password to send.',guild_ids=[944934277777326090,769823680695107594]) #
    async def password(self , ctx: discord.ApplicationContext):
        roster = Pass(title="Password menu")
        await ctx.send_modal(roster)

def setup(bot):  
    bot.add_cog(NS(bot))
#

WHY?!!!

#

Where wrong?

proud mason
young bone
soft girder
soft girder
#

I begginer blobpain

gilded niche
#

When using a select menu with user_select on mobile it only shows a small list of names. Is there any way to fix this?

grizzled sentinel
#

Can you start typing the user name and the list will update?

young bone
#

what is with Intents?

#

Does the Menus need them?

chilly spindle
#

I'm trying to make bot that supports slash commands, I'm using py-cord 2.4.0
I followed the provided code in the documentation, but I keep getting this error:

Exception has occurred: AttributeError
module 'discord' has no attribute 'Bot'
obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

chilly spindle
#

I haven't done -U py-cord yet
that could very well be it 💀

grizzled sentinel
#

Specifically step 1

chilly spindle
#

did that already

#

no, didn't do the job

young bone
#

can you show the pip list?

chilly spindle
#
Package            Version
------------------ -------
aiohttp            3.8.4
aiosignal          1.3.1
async-timeout      4.0.2
attrs              22.2.0
charset-normalizer 3.0.1
frozenlist         1.3.3
idna               3.4
multidict          6.0.4
pip                23.0
py-cord            2.4.0
python-dotenv      0.21.1
setuptools         65.5.0
wheel              0.38.4
yarl               1.8.2
young bone
#

did you also restart the editor and the terminal?

chilly spindle
#

yes

young bone
#

can you uninstall py-cord and reinstall it?

chilly spindle
#

10th time's a charm

#

done that

#

but unfortunately to no avail

#

should I move this to a thread?

grizzled sentinel
#

I think this is an issue with your terminal being in one environment while your code is running in another.

young bone
#

you mean like PyCharm?

grizzled sentinel
#

Yeah, there code is running in a virtual environment while the stuff they are doing in the terminal is not in the environment

chilly spindle
#

if I use the terminal in the ide it says already satisfied

#

im pretty sure my command prompt and ide are synced

wintry cosmos
#

Hey Folks, is it possible to create a Modal which users can be "log in" with and be redirected to a website?
the login information is generated by a command if the user has a specific role, and is added to a DB. So they dont have to provide individual passwords or usernames so that a malicious use is excluded

silent meadow
#

hey people, is this the correct way of fetching a pfp of a user?

asset = user.avatar.url(size=128)

#

async def invert(self, ctx, *, user: Option(discord.Member)):
        asset = user.avatar.url(size=128)

fervent cradle
silent meadow
fervent cradle
silent meadow
# fervent cradle You're welcome

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'str' object is not callable

#

any idea?

silent meadow
#

i mean i changed to user.display_avatar.url

#

but still doesnt work

fervent cradle
fervent cradle
#

i think because you're using self parameter

#

so you have to put this function inside a cog

chilly spindle
#

Yes

#

I believe there is an easier way

young bone
chilly spindle
#

Look at the docs for the right syntax

fervent cradle
chilly spindle
#

This should work @silent meadow

nova garnet
#

As far as I know in discord, you can't set permissions for a command from a group.
But how then to set the default permissions for the entire group of commands?

I read about it in the documentation https://docs.pycord.dev/en/stable/api/application_commands.html
But how should it work for my case?
For example, I want administrator rights to use commands from the dump group

dump = bot.create_group(name="dump")

@dump.command(name="first_join")
async def command(ctx: discord.ApplicationContext):
    print(f":/: {ctx.author} used command /{ctx.command}")
dark wagon
#

Quick and dumb question
It used to be that to invoke a bridge command from another bridge command within the same cog, you can just use
await ctx.invoke(self.other_command)
However #1642 changed it to
await self.other_command.invoke(ctx, *args, *kwargs)
Doing this, however, errors out for me with
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing. within the command being called???

grizzled sentinel
# nova garnet As far as I know in discord, you can't set permissions for a command from a grou...
dark wagon
#

Doesn't seems so. Doing that passes the Cog object itself to the command (as self.command was used, so self will be the first arg)
It would fail earlier because it will check is_app on the Cog and not ctx

nova garnet
grizzled sentinel
#

In the example they dont use self.other_commanf
Just other_command.

grizzled sentinel
dark wagon
grizzled sentinel
dark wagon
#

Command raised an exception: TypeError: invoke() missing 1 required positional argument: 'ctx'

grizzled sentinel
#

Sorry I am not thinking straight rn. I would open a thread about it and hopefully someone less tired can help.

nova garnet
#

It doesn't seem to work.
I checked on a person without roles and any admin permissions to use the command, but nothing has changed, the command can still be used.

settings = {
    'TOKEN': '---',
    'BOT_NAME': 'SubBot',
    'APP_ID': 959411069753901084,
    'ALLOWED_SERVERS_ID': [1069357003362807848],
}
import discord
import json
import time
from config import settings

bot = discord.Bot(intents=discord.Intents.all())

@bot.event
async def on_connect():
    if bot.auto_sync_commands:
        await bot.sync_commands()

dump = bot.create_group(name="dump",
                        guild_ids=settings["ALLOWED_SERVERS_ID"],
                        default_member_permissions=discord.Permissions(permissions=8))

@dump.command(name="first_join",
              guild_ids=settings["ALLOWED_SERVERS_ID"])
async def command(ctx: discord.ApplicationContext):
    _output = "Added:"
    for user in ctx.guild.members:
        if str(user.guild.id) not in user_first_join:
            user_first_join[str(user.guild.id)] = {}
        if str(user.id) not in user_first_join[str(user.guild.id)]:
            user_first_join[str(user.guild.id)][str(user.id)] = str(int(time.mktime(user.joined_at.astimezone().timetuple())))
            with open("user_first_join.json", "w") as f:
                json.dump(user_first_join, f)
            _output += (f"\n+ {user}")
    await ctx.respond(_output, ephemeral=True)

bot.run(settings["TOKEN"])
lethal hare
#

If I am extending the bot class in order to instantiate my bot, how can I implement slash commands? i.e.

class SomeBot(discord.Bot):
    
    async def on_ready(self):
        print(f'Logged on as {self.user}!')

    async def on_message(self, message):
        print(f'Message from {message.author}: {message.content}')

    //Add a slash command here
#

Or is this dumb to do in the first place

dark wagon
lethal hare
dark wagon
#

Basically just shove all the commands you need into a Cog and ship it around between where you may use it

fervent cradle
#

How to get the message url from a context menu?

#

I'm trying to get message's url:

@bot.user_command(name = "Translate")
async def translate(ctx, message: discord.Message):
  ...```
fervent cradle
#

How can i create private thread?

cerulean yacht
#

how can i use shards?

#

how much will it cost for a shard that can server around 1.2k servers?

cerulean yacht
#

can i hide commands like mee6?

cyan quail
#

though you generally don't need it around 1k guilds

cyan quail
cerulean yacht
#

will it be stupid if i try to implement it using guild commands?

cyan quail
#

you can't hide through commands since there's no (standard) api for it

#

you CAN limit commands using stuff like check decorators, but they'll still show on the user end

cerulean yacht
#

i mean if this guild need a kick command admin can add it then bot will create a guild command for this command

#

so if they remove even admisn cant see it

cyan quail
#

uhh not quite sure what you mean

cerulean yacht
#

1 min

#

i mean using this to create a guild a command when an owner or admins add a command

cyan quail
#

then yeah fill in default_member_permissions and sync

livid monolith
#
    async def play(self, ctx, *, song_name):
        """Search from spotify to add to the song queue."""
        await ctx.defer()
 
        results = sp.search(q=song_name, type='track', limit=1)
        track_id = results['tracks']['items'][0]['id']
        print(track_id)

        if ctx.author.voice is None:
            embed = discord.Embed(description=":warning: **Not in a voice channel**")
            await ctx.respond(embed=embed)
            return
        if not ctx.voice_client:
            vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
            await ctx.guild.change_voice_state(channel=ctx.author.voice.channel, self_mute=False, self_deaf=True)
        else:
            vc: wavelink.Player = ctx.voice_client
        vc.tchannel=ctx.channel
        if vc.queue.is_empty and not vc.is_playing():
          try:
              track = await vc.node.get_tracks(query=f"https://audio.shufflebot.xyz/track/{track_id}", cls=wavelink.LocalTrack)
              await vc.play(track[0])
              await vc.set_volume(50)
              await ctx.respond(f'Added `{track[0].title}` to the queue.')
          except:
              await ctx.respond(":warning: Unable to find that song.")
        else:
              track = await vc.node.get_tracks(query=f"https://audio.shufflebot.xyz/track/{track_id}", cls=wavelink.LocalTrack)
              await vc.queue.put_wait(track)
              await ctx.respond(f'Added `{track.title}` to the queue.')```

the first song plays fine then when i run the command again (should add the next song to queue) it does not play it after the first song finishes
cyan quail
#

though the sync implementation is kind of whack...

cerulean yacht
#

okay

#

can pycord do this?

cerulean yacht
#

so thats means yes 💀

#

...

#

someone here told it was not possible

#

may be my explanation was wrong back then

#

last question can i use pycord-v3?

cyan quail
#

it's "possible" but there are some issues with how pycord is structured that may make your approach inconvenient

cerulean yacht
#

after looking into codes, i think i will need to change lot of stuffs if i want to change to pycord-v3

cyan quail
# cerulean yacht like?

i mean using this to create a guild a command when an owner or admins add a command
what exactly do you mean by this? can guild admins create slash commands on your bot?

cerulean yacht
cyan quail
#

hmmmmm

cerulean yacht
#

so when owner/admin adds the plugin, i was thinking to create guild commands to get above functionality

#

is my way ok?

cyan quail
#

in theory, assuming you turn off autosync and have logic to loop through some data to call sync_commands then yeah it would be possible

cerulean yacht
#

okay

cyan quail
#

...but terribly inconvenient because you'd end up with thousands of individual guild commands instead of 3 global commands

cerulean yacht
cyan quail
#

probably not tbf

cerulean yacht
#

then okay

cerulean yacht
#

but it looks like a fun challenge

#

discord bots use ipc to communicate?
like web server and the bot

proud mason
cerulean yacht
#

okay

cyan quail
cerulean yacht
#

thanks

#

i will read it definitely want to know more

soft girder
#

Hello. I wanted to know who can help with the output of information.

soft girder
#

Check pls ↑

gleaming falcon
#

Stupid question - Are @silent messages referenced anywhere in the message object? I see MessageFlags exists for sending, but does that also refer to flags when fetching?

fervent cradle
#

how do you disable a button with a certain custom id? is that possible? (in a separate command from where the buttons are being sent)

fervent cradle
#

in pycord, if u can do msg.author.ban(), would msg.author.timeout() work as well?

north gorge
#

Bit of a long shot but I've exhausted all my googling/support seeking options, anyone know how to get something like digitalocean's app platform to correctly launch a bot? In the deploy logs I see the "bot has connected" string print out and whatnot, but then DO just says the deploy didn't work with no errors shown even.. when it appears to launch successfulllly

silver moat
north gorge
#

ah they're useless lmao

#

was hoping maybe someone here had run into a similar issue on some other app hosting platform

silver moat
#

each hosting platform is different.

north gorge
#

nbd, I'll poke around with it more, if I find a solution I'll post it here for future searchers

dusky sorrel
#

stupid question but the docs are hard to understand as theres barely any examples

#

how do i delete the original message

#

like the upper one

silver moat
dusky sorrel
#

what

#

oh

silver moat
#

you can delete the message with

dusky sorrel
#

im supposed to put ctx.message.delete after ctx.send arent i

silver moat
#

.rtfm message.delete

dusky sorrel
#

wondering why it wasnt working properly

silver moat
dusky sorrel
#

so like this

    await ctx.message.delete
    await ctx.send(string)
#

or the other way around

full basin
#

Try it and see

dusky sorrel
#

ok

#

thx

#

Neither worked.

dusky sorrel
#

yeah?

silver moat
#

and delete is a method

dusky sorrel
#

so like

#
msg = ctx.message
await msg.delete
#

doubt it tho

silver moat
#

do you know what a method is?

dusky sorrel
#

sorta

#

i forgot how to use them though.

silver moat
#

do you know basic OOP?

dusky sorrel
#

huh

#

oh

#

yeah mostly

silver moat
#

object-oriented programming?

#

so if mimi is a Cat, which has a method called eat, how would you call eat?

dusky sorrel
#

mimi.eat()

#

ctx.delete(msg)?

silver moat
#

good, so if ctx.message has a delete method, how would you call delete?

dusky sorrel
#

ctx.message.delete()

silver moat
#

good

#

but delete is async

#

so await it

dusky sorrel
#

yeah i tried that

#

oh

#

yeah its not working its throwing an error

#

wait lemme see what the error is

#

nvm its not throwing an error

#

Command raised an exception: TypeError: object method can't be used in 'await' expression

#

i thought i had to await it

full basin
#

Show the code @dusky sorrel

dusky sorrel
#
@bot.command()
async def say(ctx: commands.Context, *, string: str):
    """Says what you tell it to."""
    await ctx.send(string)
    await ctx.message.delete()
full basin
#

Show the full traceback too please

dusky sorrel
#

there is no traceback

dusky sorrel
#

because I told it to throw it

#

print(error)

#

?

#

RuntimeWarning: coroutine 'Message.delete' was never awaited

#

what do you want from me python

#

Oh now it works

#

its like plugging in a usb

#

It doesnt work then you try something else and then you try it again and it works

silver moat
#

when you edit your code. you need to restart your bot for the code to update

cyan quail
#

(use cogs)

north gorge
#

For anyone searching for this later, if you want to deploy a PyCord bot on DigitalOcean's app platform you have to select an instance of type "Worker" and not "Web".

limber urchin
#

It's better to just use a droplet though

dark wagon
limber urchin
dark wagon
#

$5/mo is common

limber urchin
dark wagon
#

(1st year only)

limber urchin
#

and after that?

silver moat
limber urchin
dark wagon
#

Which is honestly fine for 1 vCore and 2 GB of RAM

silent meadow
limber urchin
silent meadow
#
@discord.slash_command(name='invert', description="🩻 Invert the colors of a user's profile picture" )
    async def invert(self, ctx, *, user: Option(discord.Member)):
        asset = user.display_avatar.url(size=128)
    ```
dark wagon
silent meadow
#

for reference

dark wagon
#

it has unmetered traffic

silent meadow
#

I am getting an error that pfp is a str obj and it cant be callable

dark wagon
#

Installed Linux on it

#

Power draw under heavy CPU load is ~7W

silver moat
dark wagon
#

And if you go low power by using ARM like me, well

limber urchin
dark wagon
#

Kiss your x86_64 CPython packages goodbye

silver moat
limber urchin
limber urchin
dark wagon
#

I live in an area where international traffic is most served by underwater fiber lines

#

And these things go into maintenance like 3-4 times a year, which pulls my latency to the Discord voice server way up

silent meadow
#

it still just doesnt work

limber urchin
#

?tag idw

obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

silent meadow
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'str' object is not callable

#

I am trying to fetch a users profile picture and invert it

dark wagon
silent meadow
#

but this isthe error I receive

limber urchin
#

You were already told what is wrong with your code

silent meadow
dark wagon
#

.url is already an attribute, not a function that you call with (size=128)

silent meadow
limber urchin
#

Read the docs, .url is a str

dark wagon
#

Please just read the docs

#

Or at a dang minimum the hint that your IDE is trying to give you

fervent cradle
#

how do you disable a button with a certain custom id? is that possible? (in a separate command from where the buttons are being sent)

mortal cairn
#

Is it possible with the api to fetch a guild that is public or are websites like discordlookup using other methods to get information on the guild?

proud mason
#

Is this what you are taking about?

mortal cairn
#

Bot.fetch_guild() yes

silent meadow
#

.rtfm avatar

ornate swan
#

Quick question.
im using a command, where the user gets a message, with 3 Buttons and ephemeral.
And i want to edit the message and the buttons as soon the user clicks one of them, while still being ephemeral.
Do edit the message i need the message id right?
How would i give the id to a function in a diffrent file?

proud mason
#

You wouldn't need the id. You have to use interaction.edit_original_response
(In command callback)

#

OR

#

You can also do interaction.message.edit
(In the button callback)

#

@ornate swan

ornate swan
#

that makes sense

#

im using a cuntion outside of the buttoncall back

#

i can just use the interaction too right?

proud mason
ornate swan
#

yes, im calling a function in the callback

proud mason
#

Alr

ornate swan
#

since the 3 buttons im using, are doing pretty much the same think.

ornate swan
#

makes sense, ty <3

proud mason
#

Np 🙃

covert kayak
#

Can a bot send button-formatted messages in DMs using Pycord

full basin
gleaming falcon
#

I am guessing it refers to messages with a View attached

winter condorBOT
#

Done with your help thread?

Please close your own help thread by using </close:1009144375709814897> with @errant crane.

livid monolith
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/music.py", line 203, in on_wavelink_track_start
    await vc.tchannel.send(embed=embed)
  File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1616, in send
    data = await state.http.send_message(
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 365, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```

is there a way I can get my bot to send a message in the guild this error came from?
young bone
grizzled sentinel
#

If they do not want to give the bot permissions they don't get to use your bot. ¯_(ツ)_/¯

#

Oh, you want an error message to show.

#

You could just try/except the start music function.

#

You can than respond to the interaction with a message saying you don't have permission.

young bone
obsidian leaf
#

Question understanding the language python is fairly easy and hard for different individuals but I'm abit confused on python system at the moment that reading all the rules and tips that PyCharm gives me... I don't know where to begin?

full basin
#

Begin what? lol

obsidian leaf
# full basin Begin what? lol

There's different fields of coding. I only interested of data science or data analytics but I only what to learn the essentials for those fields without wasting time but I don't know where to start cause there different languages.

full basin
#

Im sure Google can answer that

dusky sorrel
#

Is it possible restart the batch process from the bot?

#

maybe using os?

#

nvm

strange cradle
#

My idea: A user will add a reaction to a message, is it possible to make the bot send a message in the same channel but in ephemeral?

silver moat
midnight torrent
#

how would you fetch the message with the id of a WebhookMessage?

#

using the get_message method returns None

round rivet
#

use fetch_message

midnight torrent
#

fetch_message doesnt appear to be an attribute of Bot

#

unless my linter is wrong

#

The ID is actually the ID of the commands interaction

#

but it thought it returned WebhookMessage

#

but im guessing thats for followups

silver moat
#

fetch_message is a valid method of channel obejcts

#

.rtfm fetch_message

midnight torrent
#

.rtfm WebhookMessage

midnight torrent
#

got what i was trying to do working thumbs_up

#

i had to store the channel and fetch it from cache to fetch the message

covert kayak
silver moat
covert kayak
#

thanks

limber urchin
#

Tbh I think just trying it would have been faster than waiting 11 hours for someone to tell you thinkCat

covert kayak
#

properly

limber urchin
#

Good thing we have examples and docs then :)

covert kayak
limber urchin
#

Then learning that should probably be step 1

sick oriole
#
async def Join(ctx):
    role_id_togive = 1036062978879004734
    member = ctx.message.author
    role = ctx.guild.get_role(role_id_togive)
    await member.add_roles(role)
    await ctx.send("{} Have Been Given The Role `{}`".format(member.mention,role.name))```
#

My code is not working, I am not sure what to do.

limber urchin
#

?tag idw

obtuse juncoBOT
#

Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

sick oriole
#

Nvm, solved it. I just needed to make the J in Join(ctx) lowercase.

fervent cradle
#

How to send the modal's callback message to a specific channel instead of sending it to the channel where the modal was opened?

fringe socket
#

Hey guys, what's the has_permissions for Managing Nicknames? Is it manage_nicknames or manage_nickname or something else?

#

Ping on reply btw

fervent cradle
#

manage_nicknames im pretty sure

#

@fringe socket

fringe socket
#

noice

young bone
fringe socket
signal comet
#

How do I get my bot to disconnect from a vc? At the moment i am using ```py
ctx.voice_client.disconnect(force=False)

limber urchin
#

okay?

#

And why do you not want to use that?

tiny dawn
#

why the hell my bot dosent respond

#

or print when i send my command

#

i am using the example

limber urchin
#

It is literally impossible for us to know unless you show your code

real frost
#

Hi, i have a question, how to create dropdowns with a choice of members? Like this

real frost
#

appreciate it

fervent cradle
#

Is it possible to start an activity (like bobble league) through a bot?

#

which would allow people to play without nitro

limber urchin
#

No

proud mason
#

.rtfm create_activity

winter condorBOT
proud mason
#

@fervent cradle check if that still works

fervent cradle
#

creating an invite probably works, but then the bot has to join and start the activity for it to work

proud mason
#

Hmm nope i dont think that's possible

tiny dawn
#

bhur

tiny dawn
#

yes?

young bone
#

did you take a look at the Docs and examples?

tiny dawn
#

i fucking copied the example

young bone
#

you try a slash command as a prefix command?

limber urchin
#

First of all, use codeblocks.
Second, show whatever error you are getting.

young bone
#

^

tiny dawn
limber urchin
tiny dawn
#

!ping

civic jayBOT
#

Pong!
Cluster 215: 19.93ms (avg)
Shard 3443: 15.38ms
Node: Ip-10-0-20-29.ec2.internal

outer wrenBOT
# tiny dawn !ping
PONG!
메세지 응답속도

720ms

API 반응속도

190ms

업타임

<t:1674133718:R>

young bone
tiny dawn
#

yes

full basin
#

By the code you provided you didn't pass intents lol

tiny hearth
#

any idea why Im getting this error since I updated Pycord?

proud mason
winter condorBOT
# tiny dawn yes

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

proud mason
#

you dont pass any intents

#

i suggest passing discord.Intents.all() when developing

proud mason
#

that looks like an error caused due to me

tiny hearth
#

Okay, when can you apply a fix?

proud mason
#

aah

#

got it

tiny hearth
#

sure, lemme paste it to pastebin cuz its quite big

proud mason
#

can you do a change in your local pycord files and test? ill tell you what to change

tiny hearth
#

sure

proud mason
#

you can always uninstall and reinstall pycord to clear these changes out

tiny hearth
#

I know

proud mason
# tiny hearth I know

cool. line 120 at discord/ext/bridge/bot.py

    async def invoke(self, ctx: ExtContext | BridgeExtContext):
        br_cmd = isinstance(ctx.command, BridgeExtCommand)
        if ctx.command is not None:
            self.dispatch("command", ctx)
            if br_cmd:
                self.dispatch("bridge_command", ctx)
            try:
                if await self.can_run(ctx, call_once=True):
                    await ctx.command.invoke(ctx)
                else:
                    raise errors.CheckFailure("The global check once functions failed.")
            except errors.CommandError as exc:
                await ctx.command.dispatch_error(ctx, exc)
            else:
                self.dispatch("command_completion", ctx)
                if br_cmd:
                    self.dispatch("bridge_command_completion", ctx)
        elif ctx.invoked_with:
            exc = errors.CommandNotFound(f'Command "{ctx.invoked_with}" is not found')
            self.dispatch("command_error", ctx, exc)
            if br_cmd:
                self.dispatch("bridge_command_error", ctx, exc)
livid monolith
#

how would i make my bot use 3 shards

solid agate
#

How can I either disabled a dropdown, or delete it, if it's in an ephemeral message? (if that's even possible)

full basin
#

The same way you'd disable or remove a dropdown from a message

solid agate
#

Then I must be doing something wrong, as I disable the select in the callback, but it ain't disabling 😛

proud mason
livid monolith
#

im not sure what to use

limber urchin
#

Why do you want 3 specifically?

livid monolith
#

well i would like to have a set amount just using 3 as an example

limber urchin
#

Why not just use AutoSharded?

sick spindle
#

Is it possible for a SlashCommandGroup have a base command e.g. having a /test along with /test subcommand1 and /test subcommand2

proud mason
#

you can specify shard id (0 indexed) and shard count (1 indexed) while creating the bot

livid monolith
proud mason
limber urchin
livid monolith
#

i would like to get it done sooner then later

limber urchin
#

That's what AutoSharded is for, so you don't have to "get it done". It will do it for you when required

livid monolith
#

at about what amount of guilds will it add another shard

proud mason
limber urchin
#

Well yeah, after a restart ofc

#

But that's the case no matter what

sick quest
#

I'm currently running my discord bot on an ubuntu server, how would I set it up to be a systemd service? I haven't really used systemd before so I don't really know where to start

limber urchin
#

Or just use pm2 to run it

spring hull
#

Is it possible to call a variable in main.py from within a cog?

limber urchin
#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

spring hull
#

well i'm trying to keep the uptime of my bot but i want the command in misc, but the code for defining when it went up in main (incase i reload the misc cog, it would be wrong). Is that the right way?

proud mason
#

you have access to the bot instance using self.bot, so yea you can use bot vars for it

spring hull
#

also does it need to be called foo?

#

or is that a placeholder?

limber urchin
#

It sounds like you need to learn more about OOP in Python

#

Because that is a very basic concept

spring hull
#

that i clearly haven't been taught

limber urchin
#

Which is exactly why you need to learn it

sick spindle
limber urchin
#

What sort of "issues"?

spring hull
sick spindle
#

It seems like the way to declare a command group is with x = discord.commands.SlashCommandGroup(name="x") and following up the subcommands with @x.command(), which would get me commands like /x a, /x b...
Of course this means I can't name another command simply just /x
In the old version of discord.py you could just declare a command group using a decorator which made creating the base command as trivial as any other command

#

Now I've tried using @commands.slash_group() to make a command but now I subcommands can't seem to find the name of the slash group defined this way

proud mason
#

discord limitation

sick spindle
#

:(

proud mason
sick spindle
#

ok thats what i was asking about, thanks

proud mason
#

👍

thorny kindle
#

Hi, I need a little help with this line, For some reasonn it only allows me to warn people who has got permission to kick people, If i add "if not" to it then it allows me to warn everyone but anyone can warn people.

limber urchin
#

sorry what?

#

You add a check for the kick_members permission, and you're surprised that only people with the kick_members permission can use the command?

solid agate
limber urchin
#

Do you not need to edit the message with the disabled select for it to update?

solid agate
#

every edit method on interaction doesn't seem to work.

#

returning Unknown Webhook

limber urchin
thorny kindle
#

You can only warn people with the kick members permission,

limber urchin
#

And what is user in your command?

thorny kindle
#

The person doing the command

limber urchin
#

No

thorny kindle
#

oh?

limber urchin
#

Send the full command

thorny kindle
#
@bot.slash_command(guild_ids = server_ids, name="warn", description = "Warn a user.")
async def warn(ctx, user:discord.Option(discord.Member, description="What user do you want to warn?"), reason:discord.Option(str)):
  if user.guild_permissions.kick_members:
    embed = discord.Embed(
      title= "You were warned",
      description= f"{ctx.author.mention} warned {user.mention} \n Reason: {reason}",
      color = discord.Color.random()
    )
    await ctx.respond(embed=embed)
  
    try:
      coll.insert_one({"_id":{"guild":user.guild.id, "user_id":user.id}, "count":1})
    except pymongo.errors.DuplicateKeyError:
      coll.update_one({"_id":{"guild":user.guild.id, "user_id":user.id}}, {"$inc":{f"count":1}})
  else:
    await ctx.respond("You don't have permission to do that!", ephemeral = True)
limber urchin
thorny kindle
#

Ohh, I think i get it, Im using user to define the person i want to warn so its messing with the permission?

limber urchin
#

You're checking if user has the permission

#

user is the person you're trying to warn

#

the code does exactly what you tell it to do

solid agate
#

every person can warn a user if that user has kick_members permission 😛

thorny kindle
#

What would i swap user with to check permissions?

limber urchin
limber urchin
solid agate
solid agate
# limber urchin Yes

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

when running self.disabled = True await interaction.edit_original_response(view=self.view)

limber urchin
solid agate
limber urchin
thorny kindle
#

hmm, Ive tried discord.Member and that just stopped the command from working.

solid agate
#

ah cool, that means I can also do the same trick to delete the message 😛

solid agate
limber urchin
thorny kindle
#

Mostly, Yes. Been learning python since i was like 14 but i never actually understood it.

limber urchin
#

Then you need to understand it before making a bot. Pycord is not a beginner friendly library.

#

Nor is any Discord API wrapper

thorny kindle
#

Ok.

drifting sleet
#

Is it possible to create a command with options that don't require any input, instead the specific option selected will do a specific action? I don't want 3 commands in a group, as they will display as 3 separate commands with a prefix/parent, I want 1 command that can do 3 actions

drifting sleet
#

umm yeah but they all require any input

young bone
#

add them optional with "required=false"?

drifting sleet
#

they will still require input when you select it, making them not required will just allow to use the command without selecting them, which I don't really want

young bone
#

There is not really anything else what you can do

#

Well I dont have an idea anymore

quick temple
#

Is it possible to use pycord to recieve interactions through an endpoint and HTTP?

pearl juniper
#

Why the first ctx.respond give discord.Interaction Object?

young bone
pearl juniper
#

Other message are Webhook

#

Based on the same

long zealot
#

Would love to lean on more experienced brains to think of the best way to do this: I'm running a megagame on Discord and have a command for players to create treaties with one another. They can list the nations involved in the treaties using commas and spaces "Federation, Mist" etc. The dream would be to have players able to autocomplete nation names, or even be restricted to only the nations available, but autocomplete can only do the first item of the list obviously. Is there any way to use autocomplete or options for this purpose/what would be the best way?

#

Thanks! I am reading the docs extensively but my head is spinning 😂

full basin
#

Instead of just one

#

Each option takes one nation

long zealot
#

Mhmmmm. Which could look kinda messy but would basically be text issuing_nation nation1 nation2 etc., and they would just leave blank the slots they don't need?

proud mason
blazing tide
#

how can i make my embed wihtour color

#

like this

storm oyster
#

Not sure but try discord.Colour.default()

proud mason
#

I think it is discord.Colour.embed_background

#

.rtfm colour.embed

winter condorBOT
blazing tide
#
color=discord.Colour.embed_background(0x2F3136)) 
#

correct right ?

storm oyster
#

Either just pass in "0x2F3136" or discord.Colour.embed_background("dark")

blazing tide
storm oyster
#

Just pass in "0x2F3136"

#

in strings

blazing tide
#

color=discord.Colour.embed_background"0x2F3136"

storm oyster
#

It only takes in one of the three arguments : dark, light or amoled

blazing tide
#

its worked

#

thanks

fervent cradle
#

Ignoring exception in on_connect Traceback (most recent call last): File "/home/container/discord/client.py", line 377, in _run_event await coro(*args, **kwargs) File "/home/container/discord/bot.py", line 1164, in on_connect await self.sync_commands() File "/home/container/discord/bot.py", line 729, in sync_commands cmd_guild_ids.extend(cmd.guild_ids) TypeError: 'int' object is not iterable

#

Does anyone know why tis is poping up

feral lintel
#

Does modal dialogs applies only to slash commands?

proud mason
#

Although you can't send a modal as a response to another modal

fervent cradle
feral lintel
young bone
#

A Modal cannot use with prefix commands

feral lintel
blissful hazel
#

I was wondering which bot i should subclass, discord.Bot or commands.Bot

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
still helm
young bone
#

anything else is the kinda the same

proud mason
zealous dagger
#

AttributeError: 'Client' object has no attribute 'commands'

#

how can i fix that

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
zealous dagger
#

discord.Bot(description="Creates an invite for you.")
AttributeError: module 'discord' has no attribute 'Bot' how abt this

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

zealous dagger
#

discord.Bot(description="Creates an invite for you.")
AttributeError: module 'discord' has no attribute 'Bot'

full basin
#

You have conflicting libraries

#

Pycord is the only discord library that should be installed

zealous dagger
#

how can i check it?

young bone
zealous dagger
#

no

young bone
#

Learn first the basic´s of Python...

full basin
#

Gotta be a joke

#

How will you even code a whole bot if you don't know python

zealous dagger
#

its from github

#

smh

distant shale
#

Line-
slash= SlashCommand(bot, sync_commands=True)

Error-

full basin
#

What the hell are you even trying to do

full basin
distant shale
full basin
#

Based of a SlashCommand object?

#

.rtfm SlashCommand

distant shale
#

Yeah yeah

full basin
#

"A class that implements the protocol for a slash command.

These are not created manually, instead they are created via the decorator or functional interface."

#

You make no sense

#

.guide

winter condorBOT
full basin
#

Read the guides

distant shale
#

Anyways good dude

blissful hazel
#

People get here without basic python knowledge?

#

I am very sad for everyone trying to answer their questions

limber urchin
#

I think it's more common for people with no Python knowledge to ask questions here than people who get proper help

#

unfortunately

#

I guess it's because most people who actually have enough Python competence also know how to read the docs NPCMechanicShrug

blissful hazel
#

True

gleaming falcon
#

What's the proper way to typehint when using get_cog?

class MyCog(commands.Cog):
  def __init__(self, bot: MyBot):
    ...
    self.other_cog: OtherCog = self.bot.get_cog('OtherCog')

PyCharm whines because get_cog returns Cog (or None). Is there a pythonic way to overcome this, or is it just best to add a # type: or # noqa annotation to the tail-end?

lost hare
#

Hey is it possible to fetch the @bridge.has_permissions(ban_members=True) Error:

Traceback (most recent call last):
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
    await self.prepare(ctx)
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 857, in prepare
    if not await self.can_run(ctx):
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 1198, in can_run
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\utils.py", line 699, in async_all
    for elem in gen:
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 1198, in <genexpr>
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)  # type: ignore
                                         ^^^^^^^^^^^^^^
  File "D:\Dev\Bottesting\venv\Lib\site-packages\discord\ext\commands\core.py", line 2138, in predicate
    raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Ban Members permission(s) to run this command.```



Just like :
**    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        if isinstance(error, commands.CheckFailure):
            await ctx.respond(f"Nur Admins dürfen diesen Befehl ausführen!", ephemeral=True)
            return

        await ctx.respond(f"Es ist ein Fehler aufgetreten: ```{error}```", ephemeral=True)
        raise error**

Just in Main Method an not in a Cog
#

the {error} is surroundered by 3 ` at the beginning and the ending

proud mason
#

Use @bot.listen() or @bot.event

lost hare
quasi musk
#

Guys need some help, is there anyway when using a slash command to add an attachments argurement to add files or no?

#

cos for some reason you are unable to use a slash command aswell as upload a file

silver moat
#

you are

errant craneBOT
#

Here's the slash options example.

quasi musk
# silver moat you are

yea I figured out how, do you know how to read the text file you just uploaded vai the slash cmd

young bone
quasi musk
young bone
#

.rtfm to_file

winter condorBOT
quasi musk
young bone
#

than download it with aiohttp

quasi musk
young bone
quasi musk
#

in pycord

young bone
#

and its not that hard to do by your own

#

only if you dont know basic python

quasi musk
young bone
#

I hope you dont use stuff like "requests"?

spare juniper
#

Thats weird

#

Shit forgot to scroll down

#

Nothing is weird

west quest
#

Hi, is it possible to check how long a member has been boosting the server for?

#

Or would I have to store the timestamp in a db

distant shale
#

Error: no attribute author

@bot.tree.command(name='join', description='Tells the bot to join the voice channel')
async def join_voice(ctx: SlashContext):
    if not ctx.author.voice:
        # User not in a voice channel
        await ctx.send("You are not in a voice channel.")
        return
    voice_channel = ctx.author.voice.channel
    if ctx.voice_client is not None:
        await ctx.voice_client.move_to(voice_channel)
    else:
        await voice_channel.connect()
    await ctx.response.send_message(f"Connected to {voice_channel}")
#

Ping me 🙂

silver moat
distant shale
silver moat
#

pip list in terminal and show output

silver moat
#

ic so you didn't even install pycord

#

?tag replit

obtuse juncoBOT
distant shale
#

It's there

silver moat
silver moat
#

?tag notpycord

obtuse juncoBOT
#

The library name is py-cord not pycord

distant shale
#

☠️ I forgot everything in 1 year☠️☠️☠️

proud mason
#

Uninstall all those you dont need

silver moat
proud mason
#

Dang

distant shale
#

It's there storage idm lol

feral lintel
#

Quick question, does @before_invoke work the same way in Slash CommandGroup as they work with prefixed group?

still helm
#

is there a way to use aliases in a bridge command?