#Basic Pycord Help (Quick Questions Only)

1 messages · Page 80 of 1

livid wolf
#

So you know how mee6 has those "profile card" things?
How do I made something like that

silver moat
#

you can use pillow to manipulate images

livid wolf
#

Alrighty

#

Last thing for now, but how would I kick the user

livid wolf
silver moat
livid wolf
#

This might help for the context.

@bot.command()
async def self_kick(ctx):
  await ctx.author.send("Why did you even kick yourself from the server?\n Well, here is the link to rejoin\n[SERVER INVITE HIDDEN FOR THIS CODE EXAMPLE]")
  await discord.Member.kick(ctx.author.id) # Might work
silver moat
#

?tag oop

obtuse juncoBOT
#

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html

There's a difference between a class and an instance. Think of it like this:

  • A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
  • An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.

Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.

mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.

There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.

silver moat
#

discord.Member is the class, not the object

livid wolf
#

Then what is the single line of code to kick the user by the user ID
ctx.author.id

silver moat
livid wolf
#

I have that

#

This is getting complex

silver moat
livid wolf
#

Yes I do

livid wolf
silver moat
#

so if discord.Member classes have a method called kick, and you have an object referenced in ctx.author, how do you call it?

livid wolf
#

discord.Member.kick(ctx.author)

silver moat
#

no?

#

kick doesn't take any arguments

livid wolf
#

So just discord.Member.kick()?

silver moat
#

no

#

you aren't arbitrarily kicking the class. you are kicking a specific object of that class.

livid wolf
#

I'm just trying to kick a single user form the server by the user ID

silver moat
livid wolf
#

Never mind

silver moat
#

?tag learnpython

obtuse juncoBOT
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

near hollow
#

I have an on_interaction and I am calling a modal, and once that modal is complete I am wanting to disable the button that triggered the on_interaction

near hollow
young bone
#

slash commands also would trigger it

near hollow
#

I have it ignoring slash commands atm

proud mason
#

It would be the best to stick to the classes

meager mica
#

bot.get message seems to only get messages from cache what method can i do to get any message

mossy holly
#

Quick question, I need to retrieve members to display their informations in a paginator.
In my callback I have this piece of code:

guild = interaction.guild
# ...
pages = []
for id in results:
  member = guild.get_member(id[0])
  
  # Mainly for the dev server, because member of the DB aren't in it (bot is used on 1 server only)
  if not member:
    member = await bot.get_or_fetch_user(id[0])
    if not member: continue    # Account deleted ?

  pages.append(await member2embed(member))

But for only 27 members it's super slow, i checked with a print and the guild.get_member() returns None so I guess it's slow because of the get_or_fetch_user().

Do you know why would the guild.get_member() return None even in the guild where everyone is (obviously the ids are correct) ?
The only member returned correctly is me

Thanks in advance 😄

waxen skiff
#

how can i make personalized choices for @discord.option()?

like the choices are per-user?

silver moat
waxen skiff
silver moat
waxen skiff
#

thats ok, thank you!

proud mason
lyric parrot
#

anyone knows why entry.target is always None when banning a member (when i use the AuditLogEntry from the audit log event)?

strange wagon
#

haven't used pycord in a while - how do i send a message in a channel without needing to trigger a command (i'm trying to send updates when a file is uploaded to a folder on box.com)

young bone
strange wagon
young bone
#

yes, it has to be in a async func

strange wagon
#

👍

light river
#

what's the function for when a bot is listening for user input

#

like how do i make a bot wait for the user to say smth and do stuff based on what they say

strange wagon
young bone
#

get_channel can be none

#

use fetch_channel

strange wagon
#

alr

#

still nothing

young bone
#

do you also start the func?

strange wagon
#

uhh in what way

young bone
#

with a task, event or command?

strange wagon
#

nope

young bone
#

...

strange wagon
#

that's where i'm stuck at lmao

young bone
#

That is basic python ;3

strange wagon
#

fr

#

idk what to trigger the function with in this case

#

@task.loop(seconds=10)?

#

wth it pinged some dude called @ta 💀

young bone
#

xd

strange wagon
#

hmm but that still does nothing

young bone
#

await newFile()

strange wagon
#

still nothing

#

it works when i use a slash command to trigger it but then that defeats the purpose of what i'm trying to do

#

xd

strange wagon
#

actually now that I think about it

#

would sending my message to a webhook make more sense?

#

actually nvm that would also require an async function

hushed cargo
#

how do i use a gif i have on my computer in an embed?
i used the code in the docs but the gif went abode the embed and not in it

file = discord.File("path/to/my/image.png", filename="image.png") embed = discord.Embed() embed.set_image(url="attachment://image.png") await channel.send(file=file, embed=embed)

hushed cargo
#

i just changed the paths

strange wagon
#

upload it to catbox, fileditch or smth and use that url maybe

#

even discord could work

hushed cargo
#

im tryna use images in my files to make adding/removing them rly easy

young bone
#

.gif?

hushed cargo
#

yeye i used .gif

strange wagon
#

hang on could i just use @bot.command and then use a while loop to keep it alive KEK

young bone
#

what?

strange wagon
#

so like

#

admin has to trigger the command and then it would start posting updates

#

this sounds stupid 💀

hushed cargo
#

file = discord.File("/Users/jade/Documents/DommyMommy/gifs/Slap.Slapped/gifff.gif", filename="gifff.gif") embed = discord.Embed(color=0xff0000, title="haiii", description="HIIIII") embed.set_image(url="attachment://gifff.gif") await ctx.channel.send(file=file, embed=embed)

#

thats my actual code

hushed cargo
#

yea

#

also- this is gonna be a hard to explain problem but heres another one

#

so im tryna make the bot use folders on my pc as options for a select menu, but to do this i needed to get the server id, buttt where the options for the select menu are set is in a class but not in a function in that class, so it couldnt access the variable

mossy holly
hushed cargo
#

Is there a way I can pass variables into a callback function?
SelectMenu.callback = callback(x=7)
Sum like that

proud mason
strange wagon
#

i'm having a massive skill issue and still can't get it to work 💀

proud mason
mossy holly
proud mason
#

try printing len(guild.members)

mossy holly
proud mason
#

thats the default and recommended behaviour. can be turned off

mossy holly
proud mason
#

sure

mossy holly
proud mason
#

you can turn it off by disabling member & guild intents. or setting chunk_guilds_at_startup to False

mossy holly
#

Oh maybe it's the intent, you need the moderate members ?

proud mason
#

?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)
mossy holly
#

I'll try this thanks

mossy holly
# proud mason ?tag intents

Ooook it works, thanks a lot (I didn't know we had to manage them in the code, I thought the dev portal was enough as I never had any problem)

normal tusk
#

command choices works with ext.bridge?

proud mason
obtuse juncoBOT
normal tusk
#

npoe it does not work

#
discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "value".```
#

however it'll be work if the option passed as a decorator

young bone
young bone
hushed cargo
#

im tryna make a select menu to pick roles, but im using a database to remember what select menu is supposed to do what- how do i make this persistent? can someone just point me in the right direction pls-

full basin
#

It's hard to create persistent views when the view itself is fed dynamically.

#

I'd create a persistent button that then fetches your database to query the roles and send the select menu.

warm grotto
#
try:
  await ctx.guild.create_role(
    name = role["Name"],
    permissions = role["Permissions"],
    color = role["Color"],
    hoist = role["Hoist"],
    mentionable = role["Mentionable"],
    icon = None if not r else None if not r.status_code != 200 else r.content,
    unicode_emoji = role["UnicodeEmoji"],
    reason = f"Restoration \"{backupid}\" initiated by {ctx.author}"
  )
except Exception as e:
  return await ctx.interaction.edit_original_response(embed=SetEmbed(ctx.guild,
    "Restoration Failed",
    f"{e}",
    discord.Color.red()))```So I'm trying out this code, but whenever I run it, I get the error:```Guild.create_role() got an unexpected keyword argument 'icon'```From the documentation, edit is a valid argument.
spring hare
#

Guild.create_role() don't have icon argument
As far as I know, you can't set icon for your role when you are creating a role, only by editing the role

proud mason
#

yea i think thats correct

#

also

#

?tag requests

obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

spring hare
cyan quail
#

(icon has been added to create_role in the next version)

proud mason
#

Oh cool

spring hare
#

Does self.bot.users returns only unique users?

gentle tundra
#
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)

Getting this error on a brand new bot

gentle tundra
#

tried switching bots too

spring hare
spring hare
gentle tundra
#

is the limit by ip?

spring hare
#

Idk?
As far as I know, per guild

gentle tundra
#

Alright

young bone
hoary plover
#

what I need to do

young bone
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

hoary plover
#

im using glitch

#

DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
WARNING: Skipping discord.py as it is not installed.
WARNING: Skipping discord as it is not installed.

silver moat
#

yeah glitch doesn't have a supported python version, consider using something else

hoary plover
#

what

#

I have a doubt

#

replit vs glitch which has better resources

silver moat
#

replit

hoary plover
#

I've been struggling on this

#

thanks

proud mason
#

.hosting

#

?tag hosting

obtuse juncoBOT
#

dynoError No tag hosting found.

hoary plover
#

wat

proud mason
#

One sec

#

See these

#

#883236900171816970 message

finite timberBOT
#
Found message through link:

Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com US https://www.vultr.com US
https://www.ovh.co.uk EU/Canada https://www.hetzner.com Germany/US
https://www.time4vps.eu Lithuania.
Self-hosting: Kinda free:
Any computer. GCP, AWS have one year free micros.
Good hosting sites (mostly free):
https://railway.app
https://oracle.com
https://render.com

Guild

Pycord

Channel

#883236900171816970

Message

#883236900171816970 message

hoary plover
#

I asked bing:

glitch provides a virtual CPU that is shared among all the projects on the same host machine. The CPU utilization is limited to 100% of a single core, which means that if your bot needs more CPU power, it may not get it. glitch also puts your full-stack apps to sleep after 5 minutes of inactivity, which means that your bot may not be online all the time.
replit provides a virtual CPU that is allocated to your repl based on your plan. The free plan gives you 0.2 - 0.5 vCPUs, which means that you can use up to 50% of a single core. The hacker plan gives you 2 vCPUs, which means that you can use up to 200% of a single core. replit also allows you to keep your repls always on with the hacker plan, which means that your bot will be online 24/7.
proud mason
#

Yeah no neither of them are good

hoary plover
#

but for free plan glitch is good ig

silver moat
#

oracle cloud free tier is very good if you have a credit card

proud mason
hoary plover
#

Im just trying to crash my discord bot as if many users use it but no one uses it

#

I will make a serious one after deciding where to host

proud mason
#

Also, never pay for replit/glitch. Just get a VPS. They start at $3 a month

young bone
#

Or a Raspberry Pi

hoary plover
#

they are vps right?

proud mason
#

Not really

silver moat
#

no, they are shared hosts

hoary plover
#

oh

#

I tried render

#

but it says 'starting with python3 main.py' and then no response

young bone
#

A Raspberry pi is great for hosting bots

proud mason
#

Yeah but they are very rare rn

silver moat
hoary plover
#

May 29 11:31:02 AM ==> Starting service with 'python3 main.py'
May 29 11:31:05 AM Traceback (most recent call last):
May 29 11:31:05 AM File "main.py", line 170, in <module>
May 29 11:31:05 AM bot.run(TOKEN)
May 29 11:31:05 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/discord/client.py", line 723, in run
May 29 11:31:05 AM return future.result()
May 29 11:31:05 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/discord/client.py", line 702, in runner
May 29 11:31:05 AM await self.start(*args, **kwargs)
May 29 11:31:05 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/discord/client.py", line 665, in start
May 29 11:31:05 AM await self.login(*args, bot=bot)
May 29 11:31:05 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/discord/client.py", line 511, in login
May 29 11:31:05 AM await self.http.static_login(token.strip(), bot=bot)
May 29 11:31:05 AM AttributeError: 'NoneType' object has no attribute 'strip'

hoary plover
young bone
hoary plover
#

it is cuz I host it on another server

silver moat
proud mason
hoary plover
#

Im too stupidlmao

#

I signup on github for render

#

and then it tell me to create a repo

proud mason
#

VPN can't fix your ping pogbruh

IP packets already take the shortest route to the destination. VPN will only slow that down

proud mason
#

Make sure it is a private repo

silver moat
#

somehow

#

The firewall adds 100 ms and VPNs bypass that

hoary plover
#

it is okay to be leaked even my bot token. cuz it is only in 7 servers and it is a gpt bot that noone uses

young bone
#

What

silver moat
proud mason
proud mason
#

Even IP ban, so you can't make new accounts too

#

Yeah not a good idea to leak your token

hoary plover
hoary plover
#

I accidently made a repo with token public and discord safety jim dm me

#

All resources for lol will stop working immediately. This action cannot be undone.
Are you sure you want to delete this Web Service?
Type sudo delete web service lol below to confirm.
Sudo Command

#

what is sudolmao

young bone
#

You should really have to remove something like that or you can have a lot of trouble with discord

hoary plover
#

oh

young bone
#

So like store it at a diff file or use an env for something like that

hoary plover
#

there are many options in render

hoary plover
#

stactic site?

#

web service?it says zero downtime

#

and where is region

#

wow

#

ohio is there

#

that will be insane

#

help

#

it is saying Unlike paid services, free services scale down when inactive. Learn more about free instance type limits. in a web service

silver moat
#

we aren't render support

hoary plover
#

but

#

you all recoment render

silver moat
#

no?

hoary plover
#

so you are technically render support

hoary plover
#

@silver moat

silver moat
#

@proud mason

young bone
hoary plover
#

WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported

hoary plover
#

yall are so friendly

young bone
#

I wonder how you mean that

hoary plover
#

?

#

bro

#

the problem has been tripled

young bone
#

?

hoary plover
#

sorry

#

idk wat happened wrong picutre ig

#

wow

#

now it is double

#

3 replies for 1 message

#

yaaayayayya

#

problem has been fixeed. Now I can spam the bot and try to make it crash as it is now render

vestal sandal
#

Wait so do I send basic pycord problems here?

#

So I watched many tutorials already, looked up on google, tried everything, but with no result

#

`@bot.command()
async def test(ctx):
buttona = Button(style=discord.ButtonStyle.red, emoji="🇦")

async def button_callback(interaction):
  user_mention = interaction.user.mention
  await interaction.response.send_message(f"{user_mention} pressed button A")
  

buttona.callback = button_callback
view = View()
view.add_item(buttona)

buttonb = Button(style=discord.ButtonStyle.green, emoji="🇧")

#--
async def button_callback(interaction):
user_mention = interaction.user.mention
await edit(content=f"{user_mention} got the answer correct. The answer was B", view=False)

buttonb.callback = button_callback
view.add_item(buttonb)

#--

buttonc = Button(style=discord.ButtonStyle.blurple, emoji="🇨")
async def button_callback(interaction):
  user_mention = interaction.user.mention
  await interaction.response.send_message(f"{user_mention} pressed button C")    
buttonc.callback = button_callback
view.add_item(buttonc)


buttond = Button(style=discord.ButtonStyle.gray, emoji="🇩")
async def button_callback(interaction):
  user_mention = interaction.user.mention
  await interaction.response.send_message(f"{user_mention} pressed button D")   
buttond.callback = button_callback
view.add_item(buttond)


await ctx.send("Wait there is a button? ![Gmoon](https://cdn.discordapp.com/emojis/1096332893334290493.webp?size=128 "Gmoon")", view=view)  `
#

This is my code for now

#

Basic message, 4 buttons: A, B, C, D

#

When pressing a, c or d, it sends a message tagging you, and saying you pressed that button

#

But I want that when button B is pressed, the message edits

#

button B is marked inbetween #-- #--

#

I've tried await interaction.response.edit_message, just like in the tutorial

#

Sadly this did not work, and pressing the button would only give me errors 😦

#

All other buttons work though

full basin
vestal sandal
#

When I press the button

full basin
#

And you should subclass views instead of doing that.

vestal sandal
#

It says Interaction failed

full basin
#

The error in the console

vestal sandal
vestal sandal
# full basin The error in the console

I changed the code a bit: ```Traceback (most recent call last):
File "/home/runner/MoonBotREAL/venv/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "main.py", line 140, in button_callback
await message.edit(content=f"{user_mention} got the answer correct. The answer was B", view=self)
NameError: name 'message' is not defined

full basin
#

It's interaction.response.edit_message

#

And that error was pretty much self explanatory, you have no message variable defined. That's why you don't copy stuff from examples without knowing what it does.

vestal sandal
# full basin And that error was pretty much self explanatory, you have no `message` variable ...

Wait, I'll send you the full code of that message:

async def test(ctx):
    buttona = Button(style=discord.ButtonStyle.red, emoji="🇦")

    async def button_callback(interaction):
      user_mention = interaction.user.mention
      await interaction.response.send_message(f"{user_mention} pressed button A")
      

    buttona.callback = button_callback
    view = View()
    view.add_item(buttona)
  
    buttonb = Button(style=discord.ButtonStyle.green, emoji="🇧")
#--    
    async def button_callback(interaction):
      user_mention = interaction.user.mention
      await interaction.response.edit_message(content=f"{user_mention} got the answer correct. The answer was B", view=self)

    buttonb.callback = button_callback
    view.add_item(buttonb)
#--
  
    buttonc = Button(style=discord.ButtonStyle.blurple, emoji="🇨")
    async def button_callback(interaction):
      user_mention = interaction.user.mention
      await interaction.response.send_message(f"{user_mention} pressed button C")    
    buttonc.callback = button_callback
    view.add_item(buttonc)

  
    buttond = Button(style=discord.ButtonStyle.gray, emoji="🇩")
    async def button_callback(interaction):
      user_mention = interaction.user.mention
      await interaction.response.send_message(f"{user_mention} pressed button D")   
    buttond.callback = button_callback
    view.add_item(buttond)

  
    await ctx.send("Wait there is a button? ![Gmoon](https://cdn.discordapp.com/emojis/1096332893334290493.webp?size=128 "Gmoon")", view=view)   
full basin
#

Ok

#

Run that code

vestal sandal
#

I did!

#

'This interaction failed'

grizzled sentinel
#

It should be ctx.respond not ctx.send

#

Send is for sending a normal message not responding to an interaction

vestal sandal
#

this makes the command not working 😦

young bone
#

what is the py-cord version?

proud mason
#

that is a very neat and simple approach

#

see this

arctic jolt
#
@bot.event
async def on_error(event_method, *args, **kwargs):
    print("on_error")


@bot.event
async def on_application_command_error(interaction: discord.Interaction, err: Exception) -> None:
    print("on_application_command_error")

neither of these are firing when an error is raised from a button click, what do?

silver moat
arctic jolt
#

else I need to make a custom view class and subclass all of them since there are quite a few

young bone
#

ctx: discord.ApplicationContext @arctic jolt

arctic jolt
young bone
#

Well, that one is for slash commands

arctic jolt
#

this is really easy to achieve in other libraries, is there no way of doing it here?

young bone
#

You could use on_interaction but that also would get trigger by slash_commands

#

Or you use try and except

proud mason
#

show pip list

#

high chance you have dpy still installed

#

lol no

#

open the terminal

#

and type pip list

#

windows or unix?

#

ah

#

do os.system('pip freeze')

#

dont do it on ready, as that would not run

#

error is before the bot starts

#

you can run that line i said at the top of your code

young bone
#

Also which topggpy is that?

#

Github or pip one?

#

Well first uninstall discord.py and py-cord and reinstall only py-cord

proud mason
#

topggpy installs dpy from what i remember

young bone
#

You have to use the github one if Im right

proud mason
#

you could use os.system for that too 😂
definitely not the best way, but it works

young bone
#

^

proud mason
#

you might find startup cmd or smth in the settings tab of the panel. try fiddling with it

zinc cloak
#

is there a way to read and edit embed attributes from a message

full basin
#

embed.attribute = newattr?

zinc cloak
#

I'm getting discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook with the following code inside a button:

        async def callback(self, interaction):
            embed = discord.Embed(
                title="testing..."
            )
            await interaction.edit_original_response(embed=embed)
            await interaction.response.send_message("Upvoted.", ephemeral=True, )
#

Ohhh wait I see the issue... the edit_original_response thing is for the message sent

#

but how do I get the original message that the button is on?

fossil mulch
#

pycord docs hella slow today or is it a problem on my end?

sly comet
#

How can I edit an interaction message/response and then reply to said message? I keep getting the InteractionResponded error

novel jay
#

Is there a way to check how much memory each shard is using when using AutoShardedBot? Or even just the pid?

hoary plover
#

render is broken.

#

it runs my same bot token 2 times

#

@proud mason

#

you recoment render

#

it is broken as hell

young bone
hoary plover
#

..

hoary plover
#

also render only provides 0.1v cpu or whatever it is

#

repl provides 0.5v

hoary plover
#

and glitch provides 1.0v cpu

zinc cloak
#

Is there a way to get a message without the channel by message id

zinc cloak
proud mason
hoary plover
#

any other

#

than render

proud mason
#

Try railway.app

hoary plover
#

ok w8

#

bro

#

End of The Line

You've been flagged for violations concerning the Railway ToS. The reason specified is "Multiple accounts".

If you believe this is in error; please reach out to us via email and we'll get you sorted!

This process is automated, new, and in constant evolution. Apologies for any inconvenience.

#

I didnt have github account when I login first to railway but now I have so I login with that and it banned me

#

any other? @proud mason

#

I dont wanna wait until I get unbanned

proud mason
#

Not a py-cord issue

hazy mango
#

i have a quick question. Is it possible to retrieve a user using their username instead of id directly or do i just have to get all members on a guild and loop over to get a user with matching name? i read the docs but could not find anything that would directly solve this

hoary plover
#

I saw there is support bout hosting in this server in the website

hoary plover
#

Hello

#

Im the new om non nom so give me respect the om nom noj has

#

oh wait he dont have any

proud mason
proud mason
#
  1. why tf are you trying to be toxic
hoary plover
hoary plover
#

I moved to pycord for a reason

#

it is fast af

#

bro

#

I used !help in carl bot

young bone
#

v3 will be even faster

hoary plover
#

and guess what?

#

it respond in 0.1 s

hoary plover
#

pip3 install py-cord install latest right?

young bone
hoary plover
young bone
#

but faster and with a clean code

hoary plover
#

I checked timedif using apollo and appolo showed 0.1s

#

and carl bot is of pycord

hoary plover
young bone
hoary plover
#

even kick command take so many code

#

imagine making a fully working moderation bot

#

kick command first checks permission then role then error handle

#

etc etc

hoary plover
#

how can I instlall it

young bone
#

They are working on it

hoary plover
hoary plover
young bone
#

eh

hoary plover
#

when I had discord.py , I import from discord import app_commands

young bone
#

if you want to use it at some point you would have to rewrite the bots

hoary plover
#

but turns out it didnt actually support app commands

hoary plover
mossy holly
full basin
#

Tries to parse a user if you provide username or username and discrim

full basin
#

Get_member only takes an ID tho?

proud mason
#

you can use get_member_named

proud mason
young bone
#

read the error?

#

lol

full basin
#

I was trynna read the message and he deleted it

#

What was it lol

young bone
#

commands was not defined

wanton pondBOT
#

⚠ Warned Haruki#8003

young bone
#

ok?

waxen whale
#

@winter condor

#

well

#

@kindred sail can you add Nziie's Utilities#9415 as overwrite with read message perms to #969574202413838426

proud mason
#

oh 👀

waxen whale
#

we might give the bot just special bot idk

#

we'll see

waxen whale
#

.rtfm user

waxen whale
#

yay

#

@proud mason

waxen whale
proud mason
waxen whale
#

-mute 920850442425102367 2d Toxic jokes

wanton pondBOT
#

🔇 Muted Haruki#8003 for 2 days

waxen whale
#

anything or anyone else?

proud mason
#

Told you. You need to uninstall dpy and reinstall py-cord

#

2.4.1 iirc

#

Yea

proud mason
#

A very bad cat i mean

#

User id - 856780995629154305

#

Probably due to topggpy

#

Try installing it with no deps

#

No dependencies is a flag in pip install

#

NGL try asking your host. They would help you

dusk pecan
#

Is it possible to get a channel ID a command is sent in? For example if I had /getchannel I would want it to reply with the ID of the channel I did that command in?

dusk pecan
# full basin Ctx.channel.id?

We're gonna pretend like I didn't already do that, but forgot to actually setup a response so when I ran the command nothing came up so I thought that wasn't it. I should generally just read, might help.

empty crypt
#

hi

grizzled sentinel
#

Hello :)

empty crypt
#

Im haruki alt. sorry for bypassing mute. this time I have a problem

#

so I join with alt

#

Ill leave as soon as problem fix

#

Traceback (most recent call last):
File "main.py", line 56, in <module>
discord.Option("member", "The member to kick", discord.OptionType.user, required=True),
AttributeError: module 'discord' has no attribute 'OptionType'

#

@bot.slash_command(name="kick", description="Kick a member from the server", guild_ids=[...], options=[
discord.Option("member", "The member to kick", discord.OptionType.user, required=True),
discord.Option("reason", "The reason for kicking", discord.OptionType.string)
])
@commands.has_permissions(kick_members=True)

#

this is my serious bot

#

@grizzled sentinel

grizzled sentinel
empty crypt
#

ok wwait lemme try

#

Traceback (most recent call last):
File "main.py", line 56, in <module>
discord.Option("member", "The member to kick", discord.user, required=True),
TypeError: Option.init() takes from 1 to 3 positional arguments but 4 were given

#

@bot.slash_command(name="kick", description="Kick a member from the server", guild_ids=[...], options=[
discord.Option("member", "The member to kick", discord.user, required=True),
discord.Option("reason", "The reason for kicking", discord.string)
])
@commands.has_permissions(kick_members=True)

#

@grizzled sentinel

#

pls respond to this I gtg

grizzled sentinel
#

Please look at the docs

#

.rtfm discord.Option

grizzled sentinel
#

Your arguments are out of order

silver moat
#

they left the server 💀

flat blade
#

Is it possible to run a task at every system clock minute?

young bone
flat blade
#

How would it be done?

proud mason
flat blade
#

Yes, but how would I set the task to run at every system clock minute?

waxen whale
#

nickname checks out :^)

proud mason
slender abyss
#
File "C:\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\Sumit\Discord Bot Mystic\Test Bot\main.py", line 24, in select_callback
    item = MyButton(self.ctx, f"{select.values[0]}")
  File "c:\Users\Sumit\Discord Bot Mystic\Test Bot\main.py", line 46, in __init__
    self.label = label
  File "C:\Python310\lib\site-packages\discord\ui\button.py", line 194, in label
    self._underlying.label = str(value) if value is not None else value
AttributeError: 'MyButton' object has no attribute '_underlying'

What is this error

#
class MyButton(discord.ui.Button):
    def __init__(self, ctx, label):
        self.ctx = ctx
        self.label = label
        super().__init__(style=discord.ButtonStyle.blurple, label=label)
    
    async def callback(self, interaction: Interaction):
        if interaction.user == self.ctx.author:
            await interaction.response.send_message(f"{self.label} clicked ", ephemeral=True)
#

This is the button class where i get error

proud mason
#

Don't set label like that

#

Pass it to the super init

slender abyss
#

Ok

lusty mantle
#

hello, I am doing translation for my bot and I would like to know if there is a way to access to user locale language. I tried to search in the docs but didn’t able to find anything lol

lusty mantle
#

ok, I just find it, it’s ctx.locale

#

I think there is an error in the docs because it’s written the locale of the guild but it’s the user's one

young bone
rare ice
#

i swear to ducking god i hate python sometimes

# Error
TypeError: register_config() got an unexpected keyword argument 'default_embed'```

```py
# Code
bot.config_class.register_config(key='ticket_created_embed', default_value=None, config_type='EMBED', add_to_help=True, description="Embed sent in the created ticket channel when a user creates a ticket", notes="Use the embed builder in the `config set` command to customize this embed.", default_embed={'description': 'Hey, {user.mention}! Welcome to your ticket. Support will be here soon to assist you. In the meantime, please explain what you need assistance with.', 'color': 5793266, 'footer': {'text': '{guild.name}', 'icon_url': '{guild.icon}'}, 'author': {'name': 'Created by {user.full_name}', 'icon_url': '{user.avatar}'}, 'fields': [], 'title': 'Ticket #{ticket.number}'})
# Function
# `bot.config_class` is a `Config` class, here is the function that I am using
  def register_config(self, key: str, default_value, config_type: str, default_embed: dict=None, description: str=None, notes='', add_to_help: bool=False):                                         # ^^^^^^^^^^^^^^^^^^^
    # stuff that doesn't matter, since the error is in the function usage

It's weird because with one bot it works, and another it doesn't.

young bone
#

default_embed?

rare ice
zinc cloak
#

that's so weird

near hollow
#

Is it possible to reply to a message from a on_message event?

zinc cloak
#

message.reply or something

zinc cloak
#

Does this help

zinc cloak
meager mica
#

So I store usernames and descriminator in database is there a way I can migrate from that to new usernames like convert username and descriminator to username through oycord lib

#

If that makes sense

silver moat
#

why do you store them to begin with

normal tusk
dense gorge
#

Alright, here we are.

#

I know how to query whether a message was sent from within a specific channel, but I understand that applying a listener for every message my bot receives (and then filtering via a MySQL lookup) is...impractical.

#

I want to spawn a listener function for on_message for threads, as determined at runtime.

#

Such a thing even possible?

#

That is to say, I'll have a list of threads that I want to be notified of every message sent within them.

#

I'm open to hacky solutions so long as they're optimized. Perhaps I could start listening with a /slash command, and for as long as that interaction token remains open (15 mins), the bot listens?

#

Oh, how about something recursive? Maybe a task that listens for a message and calls itself when it hears it.

normal tusk
#

@dense gorge what exactly the thing that you looking for or what you wanna achieve

dense gorge
#

I have a list of threads that will be extended and shortened throughout the use of my bot.

#

I want to listen for any messages sent from within these threads-- I don't want to listen for messages sent anywhere else.

#

I could just have an on_message() listener and then get the message details to determine if that message was sent from within a thread that I care about listening to.

#

But if it's triggering for every single message that my bot receives, then it'll be doing an incredible amount of calls for that function that checks whether it's from one of those important threads.

#

Way too taxing on my database.

normal tusk
dense gorge
#

Yeah, I'm with you.

dense gorge
dense gorge
#

What I need is a selective listener.

normal tusk
dense gorge
#

That requires the cache remain in memory, which isn't a guarantee.

#

I want my bot resistant to resets.

#

(I expect I'll be restarting it quite a bit while I improve it).

#

My current solution is to log it into a MySQL database.

normal tusk
normal tusk
silent meadow
#

how do I identify if a slash command is used as a reply to a message? and how do I fetch the details about that message... such as the author of the message or the message content?

silent meadow
#

but how do I check for it?

#

like is it an event?

#

or is it an if, else statement?

dense gorge
#

In the slash command, you're given a ctx: discord.ApplicationContext as an argument.

#

All you need to do is something like this:

silent meadow
silent meadow
#

so like

@discord.slash_command(name = "", description = "")
async def command(self, ctx: discord.ApplicationContext):
  content = ctx.message.reference.content
normal tusk
#

.tias

winter condorBOT
normal tusk
#

:)

silent meadow
#

very funny

#

its like my code is working and i dont wanna touch it

dense gorge
# silent meadow <:ThinkO_O:881521960192999424>
    name = "example-command",
    description = "shows you how to check for whether this command was used as a reply")
async def example(ctx: discord.ApplicationContext):

  wasReply = ctx.message.reference

  return```
silent meadow
#

so i am asking david b4 hand if it would mess things up

dense gorge
silent meadow
dense gorge
#

Just reference. I believe. Haven't texted.

silent meadow
#

hmmm

#

okay

normal tusk
dense gorge
# normal tusk <:ok:1091369044852101221>

So, you might be onto something, but I'm not sure that I understand. So you're suggesting a listener function for the database that determines if there's a change-- what, like a 10 second loop that compares the stored database thread IDs with maybe a SHA checksum?

#

Or I guess, I could just check the db file itself for the last modified time metadata.

normal tusk
dense gorge
#

So then if/when it notices a change, loads those new channels and only those new channels into a list variable?

dense gorge
#

And then that is my efficient filter to apply to on_message?

normal tusk
silent meadow
#

ctx.message gives None

normal tusk
dense gorge
#

Well, that blows.

silent meadow
#

real

#

i forgot

normal tusk
#

(invoke)

silent meadow
#

LMFAO

#

nvm nvm

#

i will make it a command

#

@commands.Command() 👌

normal tusk
#

👀

dense gorge
#

Like a test command? That'll work, but ahhh.

#

Slash commands are so much neater.

normal tusk
#

fr

dense gorge
#

Hm. If the "replied to" attribute (reference) is only visible to messages, and messages are None if it's a slash command, then... hmm...

silent meadow
#

yea

dense gorge
#

I'll do my own testing. Hold on.

silent meadow
#

🤔

normal tusk
#

👀

silent meadow
dense gorge
#

The what.

silent meadow
#

.rtfm ctx.message.reference

winter condorBOT
#

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

silent meadow
#

.rtfm message.reference

silent meadow
#

alr

dense gorge
#

Haha wow.

#

Okay. So.

#

Turns out there's no easy way to do what you want to, but uh, there is a way. Reeally gross, though.

silent meadow
#

😔

dense gorge
#
  1. Get the channel that the command was invoked in using ctx.channel.
  2. Get the message history of that channel (requires the read_message_history permission as well as the proper Intent in your code and the correct scope in your Developer Portal app).
  3. Scan through those messages until you find the one with a reply to it.
#

Which, wait. Is there even a way to tell if a message has been replied to, based only on the message that's being replied to?

#

Or is that information only attached to the message that's actually doing the reply?

#

Hm.

#

Let me keep looking.

dense gorge
# silent meadow 😔

Nope, impossible. When you have a message pulled up to Reply to, slash commands bypass that. Slash commands can't be used as a reply.

#

So even if you could get the messages that refer to a message, it wouldn't show the slash command.

#

However, a bot itself can reply to another message.

#

Here's an idea:

#
  1. Some slash command that looks like /bot facepalm @you (mentioning someone within a slash command doesn't ping them. It also doesn't even notify them at all if the command is ephemeral).
  2. The bot then responds to your command by finding the latest message sent by @you and reacts to it with the facepalm option.
silent meadow
#

i am using normal commands @dense gorge its oke

dense gorge
normal tusk
#

larking :)

#

👀

silent meadow
#

look at this

#

i replied to their mssage and amari came up with the proile of ctx.message.author of the replied message

dense gorge
#

Dang. It works.

normal tusk
#

how about slash commands

dense gorge
#

I just typed like ten minutes for no reason LOL

#

So it would look something like...

  name = 'reply',
  description = 'reply to a user.')
async def replyToUser(
  self, 
  ctx: discord.ApplicationContext,
  replyTo: discord.Option(
    discord.Member,
    name = 'user',
    description = 'Who to reply to?',
    required = True
    )):
  responseContent = f'Could not find a message from {replyTo} in the last 10 messages in {ctx.channel.name}!'
  channel = ctx.channel
  async for message in channel.history(limit = 10, oldest_first = False):
    if message.author == replyTo:
      ctx.send(text = 'Replied.', reference = message)
      responseContent = f'Reponded to {replyTo}!'
      continue
  ctx.respond(text = responseContent, ephemeral = True)
  return```
normal tusk
#

i hate those errors tbh sad

silent meadow
#

but i dont want that sir

silent meadow
dense gorge
#

What it would look like is /bot rank @ThatStupidDuck and you'd get the result you're looking for with slash commands.

silent meadow
#

no

dense gorge
#

?

silent meadow
#

wait lemme tell you what i am working on

#
@commands.Command()
    async def mock(self, ctx: discord.MessageReference):
        test_str = ctx.message.reference.content
        res = ""
        for idx in range(len(test_str)):
            if not idx % 2:
                res = res + test_str[idx].upper()
            else:
                res = res + test_str[idx].lower()
        await ctx.respond(res)
#

see

#

for example

silent meadow
#

and the bot will mock the text

#

and send

#

FoR eXaMpLe

dense gorge
#

Are you going to be replying to messages as soon as the person sends them?

silent meadow
#

no.

#

i dont want a slash command at all

#

😭 what has gotten you

dense gorge
#

What??

silent meadow
#

i changed my mind

dense gorge
#

Did you now.

#

I thought that switching over to message based commands was a compromise.

#

I see.

proud mason
dense gorge
#

What's that?

proud mason
#

That gives you ctx.message

dense gorge
#

Holy shit!

#

I didn't know that existed.

proud mason
#

Lol

dense gorge
#

What's that called?

proud mason
#

You can have cmds for users or messages

dense gorge
#

Literal sparkles in my eyes.

#

This opens the door to so much.

proud mason
#

Mhm

dense gorge
#

Thanks.

proud mason
#

And if you want to get some input too, send a modal to it

dense gorge
#

How far we've come since !help...

silent meadow
#

i am not that literate

#

plus just like david

#

many people dont know thye exist

#

so it would be of no use

proud mason
#

There are people who don't know slash cmds too...

warm grotto
silent meadow
#

om bhai thats why

warm grotto
#

Right

silent meadow
#

i think you can just put none to it

warm grotto
#

But, I would like to restore unicode_emojis like 💸 for example

proud mason
warm grotto
#

I'm using 2.2.2

proud mason
#

Yeah update to 2.4.1

dense gorge
#

(Which is 😀 btw).

warm grotto
warm grotto
dense gorge
#

And is ROLE_ICONS in guild.features?

warm grotto
# dense gorge And is ROLE_ICONS in guild.features?

I know that when you pass icon as a parameter in a server that does not have ROLE_ICON in guild.features, it would not actually show until it has been activated, which is what I want and does not throw any errors. Would the icon parameter act the same as unicode_emoji?

dense gorge
warm grotto
#

Looks like Nelo recently added unicode_emoji, but has not made it possible yet to have it act as icon. I might add that as a suggestion

dense gorge
#

Ope lol.

#

There you have it.

warm grotto
#

Yeah, updating it to the latest version instead of the stable version worked

wanton drift
#

How do you add another input for slash command?

proud mason
empty crypt
#

hi

empty crypt
dense gorge
#

Hey, question.

#

discord.ui.role_select() == fucked??

empty crypt
#

thanks

dense gorge
#

Does anyone know how that works? It's throwing weird errors. I built a helper function that returns a view with a role_select component on it and it's saying this:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Item not <class 'function'>

#

I suspect only string_select works.

proud mason
#

You didn't call the function?

dense gorge
#

Nope.

#

discord.ui.role_select() yields a bizarre 404 error when sending the component, and discord.ui.select(select_type = discord.ComponentType.role_select) yields the weird function error.

#

Here's the code:

proud mason
#

that is the decorator

#

Not the class

dense gorge
#

Oh. My bad.

#

Well, point stands for the first one.

proud mason
#

Use discord.ui.Select

#

Send full error and your code

dense gorge
#

I really fell for it.

#

I really thought it was a shortcut like it says.

#

Nope, you gotta specify the old fashioned way with discord.ui.Select(select_type = discord.ComponentType.role_select).

#

I guess.

#

But yes, that works now.

wanton drift
dense gorge
#

The choice is, by nature, a variable.

dense gorge
# wanton drift how do i make one of the choices a var? would you just do it like discord.app...

It would look something like this:

        name = 'example',
        description = 'does the thing you want')
async def exampleCommand(
  self,
  ctx: discord.ApplicationContext,
  optionVar: discord.Option( ##The variable name of the choice here is optionVar
    str,
    name='detail',
    description='How in-depth should it be?',
    required=False,
    choices=[
      'simple',
      'complete',
      'comprehensive'
      ],
    default='simple'
    )):
  ctx.respond(text = f'You just said {optionVar}.')
  return
dense gorge
proud mason
dense gorge
#

Aha.

#

That is good info to know.

wanton drift
dense gorge
#

Same deal.

wanton drift
#

just create new one?

dense gorge
#
        name = 'example',
        description = 'does the thing you want')
async def exampleCommand(
  self,
  ctx: discord.ApplicationContext,
  optionVar: discord.Option( #First option here
    str,
    name='detail',
    description='How in-depth should it be?',
    required=False,
    choices=[
      'simple',
      'complete',
      'comprehensive'
      ],
    default='simple'
    ),
otherOptionVar: discord.Option( #Second one
    str,
    name='Other',
    description='Mhm',
    required=True'
    ),):
  ctx.respond(text = f'You just said {optionVar} and {otherOptionVar}.')
  return```
wanton drift
#

ok

dense gorge
#

Hold on.

wanton drift
gray juniper
#

Python Version: 3.9.16

#

pip is also newly installed

#

uhh how do I fix this 💀

somber pelican
gray juniper
#

no module named pip3

somber pelican
gray juniper
#

I tried it

#

same error

proud mason
gray juniper
#

I installed py-cord from dev branch

somber pelican
#

hm

gray juniper
#

it looks like its installed

#

look at the highlighted part

somber pelican
#

pip install --upgrade pip?

gray juniper
#

let me try

somber pelican
#

actually nvm

#

python3 but no pip3 hm

gray juniper
#

oh it had pip 9.0.01

proud mason
#

Try python3.9 -m pip ...

gray juniper
#

it installed pip 20.3

#

how do I uninstall python2

somber pelican
proud mason
#

Oh

#

3.8 is needed

somber pelican
#

ahh

proud mason
#

Install the latest python 3.11 @gray juniper

#

Wait dont

proud mason
proud mason
gray juniper
#

Hmm

#

so should I uninstall python2 and python 3.16

#

3.6*

#

I uninsatlled py2 and py3

#

and installed pip latest and py 3.9

#

that should work right?

young bone
#

I would go for 3.11

gray juniper
#

@young bone I installed python 3.11 and uninstalled everything

#

but how should I install pip now

#

bcz if I use apt-get install python3-pip it also installed python 36

#

3.6

young bone
#

How did you install it?

gray juniper
#

python 3.11?

#

sudo apt install python3.11 and before that I installed PPA

somber pelican
#

@gray juniper what if you just do pip install py-cord without the requirement?

grizzled sentinel
somber pelican
#

Congratulations

#

Which version did it install?

meager mica
#

I didn't wanna fetch thousands of usernames every time someone used leaderboard command

grizzled sentinel
meager mica
#

Is there any way to convert username and descriminator the id

spring hare
grizzled sentinel
meager mica
#

Do I need server members intent for that

grizzled sentinel
#

Most likely.

hushed cargo
#

is there a way to assign a select menu option an id?

proud mason
#

.rtfm get_member_named

winter condorBOT
proud mason
proud mason
proud mason
#

Use that in the list of choices

#

Set a value

hushed cargo
#

value is annoying- but oki

proud mason
#

Not sure but the value needs to be a string. Convert it to an int

hushed cargo
#

and is there a way to make persistent view without subclassing the view?

hushed cargo
#

how to i use .add_item with a subclassed view?

#

SelectRoleView().add_item(SelectMenu) await ctx.channel.send(view=SelectRoleView()) ServerId = ctx.guild.id embed = discord.Embed( title="**Role Select Menu Created!**", description="**^-^**", color=GetColor(ServerId) ) await ctx.respond(embed=embed, ephemeral=True)
thats the code
and heres the code for the view
class SelectRoleView(View): def __init__(self): super().__init__(timeout=None)

#

im trying to add the select menu to it ant it gave this error message
"discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message"

#

the add_item just isnt working

#

you could use the discord integration thing in server settings to only be able to use it in one channel

#

could do

#

np!

odd prairie
hushed cargo
#

i did

#

i think the problem was the way i used add_item with a subclassed view

odd prairie
#

Oh, I did not see the SelectMenu thing.

odd prairie
hushed cargo
#

nu

#

idk how, i think for some reason add_item isnt working with the subclassed view

#

wdym?

odd prairie
#

^^

hushed cargo
#

i think if you set the argument to only accept one argument

odd prairie
#

Your argument must be *values (will get everything that's after your command) then to make that into one sentence you can do sentence = " ".join(values)

hushed cargo
#

yea was abt to say

odd prairie
#

np

hushed cargo
#

add spaces where?

#

im sorry i dont get what you mean

spring hare
#

"\n" but I think this is just fields

#

Check guide

#

oh, bruh

#

Not this spaces

#

Bruh

proud mason
#

lmao

hushed cargo
#

Is there a way to use .add_field with a subclassed view? I'm tryna make it persistent

proud mason
#

persistent views and embeds arent related tho

hushed cargo
#

You can add_feild to a view-

#

Adding a field to a view is kinda related to persistent views

proud mason
hushed cargo
#

Ye

proud mason
#

.rtfm view.add_field

winter condorBOT
#

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

proud mason
#

uh

hushed cargo
#

To add a button orselect menu

proud mason
#

oh you mean add_item

hushed cargo
#

Omg- I'm dumb thank you 😭

proud mason
#

lol so your issue is solved?

hushed cargo
#

Nono

#

Im using add_item

#

But when I try to use it with a subclassed view it doesn't add it

proud mason
#

ah

#

how are you using it?

#

can you show the code?

hushed cargo
#

Can't show rn but I'll explain

#

The view is its own class that all that's in it is the init function, then in the function for the command I do view().add_item(Select Menu)

#

When I did the same thing when view = View() and no problems

#

I just wanna do it like this bc using variables from one class in another is so annoying

#

And itneeds to be persistent but the select menu uses paramaters you set with 5he command

sleek arch
#

How can I make a persistent View in a cog? When I try, I get the error:

discord.errors.ExtensionFailed: Extension 'cogs.tickets' raised an error: RuntimeError: no running event loop

young bone
sleek arch
#

How do I register it as persistent? Not in a cog I could put in on ready client.add_view(view())

young bone
#

But you know basic Python?

proud mason
#

Use an event listener

sleek arch
livid wolf
#

How would you mark an embed/embed image as a spoiler?

coarse cargo
young bone
#

It is possible

coarse cargo
livid wolf
#

Yeah

normal tusk
#

any idea to subclass the discord.SlashCommandGroup object?

full basin
#

why would you sublcass it

normal tusk
#

and use the common parents between them in each file

normal tusk
#

@cyan quail there is a way to that NOOOO

normal tusk
hushed cargo
#

`
import discord
from discord.ext import commands
from BaseCommands import *
from discord.commands import Option
from discord.ui import View, Button, Select
from discord.utils import get
import discord.utils

global options
class SelectRoleView(View): # Create a class called MyView that subclasses discord.ui.View
def init(self):
super().init(timeout=None)

MenuOptions = options.split(",")
optionsss = []
for MenuOption in MenuOptions:
    RoleId, Label, Description, Emoji = MenuOption.split()
    option = discord.SelectOption(
        label=Label,
        description=Description,
        emoji=Emoji,
        value=RoleId
    )
    optionsss.append(option)

if multiple == "false":
    MaxValues = 1
else:
    MaxValues = len(MenuOptions)
SelectMenu = Select(# the decorator that lets you specify the properties of the select menu
    placeholder = placeholder, # the placeholder text that will be displayed if nothing is selected
    min_values = 0, # the minimum number of values that must be selected by the users
    max_values = MaxValues, # the maximum number of values that can be selected by the users
    options = optionsss,
    custom_id= "RoleSelectMenu"
)

async def callback(self, interaction):
    global SelectMenu
    ServerId = interaction.guild.id
    RoleIds = []
    for x in SelectMenu.options:
        RoleIds.append(x.value)
    SelectedRoleIds = SelectMenu._selected_values
    guild = interaction.guild
    member = guild.get_member(interaction.user.id)
    for RoleId in RoleIds:
        if RoleId in SelectedRoleIds:
            RoleIdss = RoleId.split("/")
            for RoleIdd in RoleIdss:
                role = get(guild.roles, id=int(RoleIdd))
                if role not in interaction.user.roles:
                    await member.add_roles(role)
        else:
            RoleIdss = RoleId.split("/")
            for RoleIdd in RoleIdss:
                role = get(guild.roles, id=int(RoleIdd))
                if role in interaction.user.roles:
                    await member.remove_roles(role)
    try:
        await interaction.response.send_message("")
    except:
        pass

class add_select_roles(discord.Cog):
def init(self, bot):
self.bot: commands.Bot = bot
@bot.slash_command(description="add a select role menu")
@commands.has_permissions(administrator=True)
async def add_select_roles(self, ctx, placeholder: Option(str, "what will show in the menu when you havent selected anything"),options: Option(str, "'RoleId/RoleId label description emoji' add multiple by seperating them with commas"), multiple: Option(str, "true or false, anything else will set it to true, default: false", required=False, default="false")):
if ctx.channel.type == discord.ChannelType.private:
await ctx.respond(embed=YouCantDoThatInDms_embed)
return

    await ctx.channel.send(view=SelectRoleView)
    ServerId = ctx.guild.id
    embed = discord.Embed(
        title="**Role Select Menu Created!**",
        description="**^-^**",
        color=GetColor(ServerId)
    )
    await ctx.respond(embed=embed, ephemeral=True)

def setup(bot):
bot.add_cog(add_select_roles(bot))
`

heres my code its not letting working because subclassing View makes it hard to get the commands paramaters, how do i get them?

hushed cargo
#

im trying to make a persistent select menu, that you create with a command, how to i make it work? because the options are determined by paramaters in the command the persistence isnt working

#

please someone point me in the right direction

meager mica
#

When I do that I usually try to store what I need in database

#

Is their another way probably but I couldn't find it for my use cases lol

hushed cargo
#

lmao exactlyyy, thats my problemmm XD

#

any chance you could dm me so i could ask you some stuff?

meager mica
#

I just worked around it with database

hushed cargo
#

yea im tryna do that but adding a persistent view makes it weird

hushed cargo
#

please be more specific

#

wut happens when you do it?

#

error?

#

try running your command and giving it this
1+1

#

wuts that mean

#

oki what is os.environ["BOT_OWNER"]?

#

try copying your id and put that in the code

#

i believe ids and int

#

oki

#

make surein the env

#

its an integer and not a string

#

that works too

rare ice
#

You have to

hushed cargo
#

ahhh

#

cogs

rare ice
#

You have to restart the bot

hushed cargo
#

no- i use cogs and i can

rare ice
#

Not with slash commands

hushed cargo
#

i use slash commands and cogs work?

rare ice
#

I wouldn’t recommend doing that but you could. If you have tasks with discord.ext.tasks you will run into problems.

rare ice
hushed cargo
#

oh? how so?

rare ice
#

Slash commands won’t get re-registered

#

Meaning they won’t update

hushed cargo
#

im so confused- ive been doing this for ages with mo problems

#

no*

rare ice
#

Are you going to seriously argue with me?

hushed cargo
#

im genuinely confused, bc ive literally been doing it and its been working fine

rare ice
#

Under certain circumstances, it causes problems

hushed cargo
#

plus they dont use slash commands so they so could use cogs-

rare ice
#

I wasn’t referring to them, you asked me the question

hushed cargo
# rare ice Are you going to seriously argue with me?

oki- well idk wut these curcumstances are but ive used cogs for slash cmmands and have tested out reseting them a bunch and have found no problems then you respond like this to me asking a question- like bruh, wasnt arguing, i never heard it could cause problems

versed fern
#

Reading challenge lmao

#

The error tells you exactly what to do

#

What error does it return

#

You just added a random loop to your file

#

It seems like you wanna load all cogs at start-up

#

But you'd need an on ready event for that

#

One sec, trying to figure out how the bot commands work

#

.rtfm on_ready

winter condorBOT
versed fern
#

If you don't know what an event is, you'll have to read the docs

versed fern
#

They're pretty intuitive

#

There's a get started guide somewhere as well as an FAQ

#

After that you'll just search for an event or whatever and find specific Information on what you wanna archive

#
spring hare
#

Do you know any templates for discord bots? (with pycord)

#

Not fully built bots, just templates

spring hare
#

Send your code

#

As I understand it, you have a text command that takes arguments, but when you call the command, you do not pass the argument, and therefore this error appears

#

For example: !load

#

You either need to add on_error or make arguments not required

#

And I also think your on_ready just don't work

#

Add @bot.event

#

? Return your async def on_ready():

#

And just add decorator

normal tusk
#

🐈

spring hare
#

TypeError: object NoneType can't be used in 'await' expression Your tried to await None

#

Oh... Sorry

#

Uhm

#

Oh, not that

#

await setup(self)

#

I'm confused 💀
I think there are some problems in await bot.load_extension(f"cogs.{filename[:-3]}")

coarse spire
#

you can't use "await" in load_extension

#

just remove the await

spring hare
#
  1. add @is_owner instead of if ctx.author.id == int(os.environ["BOT_OWNER"]) and add owners to your commands.Bot
  2. I think your tried to load or unload cog that just don't exist
#

@coarse spire

coarse spire
#

hmm

ocean pumice
#

Hey, what should I write in a webhook in order to get this little grey box with the time left in a message?

#

Thanks

young bone
#

@fervent cradle
Dont load the cogs at the on_ready event

#

If you get the await error you have something else installed and py-cord

#

Can you show the pip list?

#

Do you know basic python?

full basin
#

Then it's the same thing lol. Just replace install with list

young bone
#

Uninstall all 4

#

After that install only py-cord

#

not pycord

coarse cargo
young bone
hushed cargo
#

is there a way i can use @bot.event to run something whenever any select menu is used?

#

anything like async def on_raw_reaction_add(payload):

normal tusk
#

smth like djs handlers

hushed cargo
#

bc if i could do that then i wouldnt need a database to have a select menu persistent

normal tusk
hushed cargo
#

bc the way im creating select menus is with a command, that paramaters decude whats in the select manu, so i cant rly just add the view when the bot starts

normal tusk
#

.rtfm discord.on_interaction

young bone
#

You have to create a view class to have it persistent?

normal tusk
#

^ this may help :)

young bone
#

on_interaction also triggers slash commands

normal tusk
hushed cargo
#

im tryna make a command to add a select menu for roles

#

so the contence of the select menu depends of the paramaters of the command

normal tusk
#

this may fix all that pain

hushed cargo
#

ive triied to make it persistent by subclassing view but it no work

hushed cargo
#

can i dm you to explain it better without slowmode?