#Basic Pycord Help (Quick Questions Only)

1 messages · Page 11 of 1

peak wing
#

i jus sent all my code

#

not in order

#

i wrote it

cyan quail
#

...why would you send your code out of order?

peak wing
# cyan quail ...why would you send your code out of order?






@client.command()
async def ui(ctx, user: discord.Member = None):
  if user == None:
    user = ctx.author
  if user.status.name == 'idle':
    user.status.name = abcd
  
  pos = sum(m.joined_at < user.joined_at for m in ctx.guild.members if m.joined_at is not None)
  joined = user.joined_at.timestamp()
  creation = user.created_at.timestamp()
  
  embed = discord.Embed(description = f'{user.mention}', color=0x303135)
  embed.set_thumbnail(url = user.avatar.url)
  embed.set_author(name = f'{user} ({user.id})', icon_url=user.avatar.url)
  
  embed.add_field(name = 'Joined:', value = f'<t:{int(joined)}:R>', inline=False)
  embed.add_field(name = 'Created:', value = f'<t:{int(creation)}:R>', inline=False)
  embed.add_field(name = 'Status:', value = f'{user.status.name}', inline=False)
  embed.add_field(name = 'Activity:', value = f'{user.activity}', inline=False)
  if len(user.roles) > 1:
    role_string = ' '.join([r.mention for r in user.roles][1:])
  embed.add_field(name="Roles:", value=role_string, inline=False)
  embed.set_footer(text = f'Join Position: {pos}')
     
  await ctx.send(embed=embed)```
cyan quail
#

ok so

#

just make it a variable instead

#

like status = user.status.name, then edit status

peak wing
#

hmm

cyan quail
#

some objects you can't just write to directly

peak wing
#

so status = user.status.name, and if status == 'idle': and i can go on from there?

cyan quail
#

yeah

peak wing
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'status'```
#
async def ui(ctx, user: discord.Member = None):
  status = user.status.name
  if user == None:
    user = ctx.author
  if status == 'idle':
    status = abcd
  
  pos = sum(m.joined_at < user.joined_at for m in ctx.guild.members if m.joined_at is not None)
  joined = user.joined_at.timestamp()
  creation = user.created_at.timestamp()
  
  embed = discord.Embed(description = f'{user.mention}', color=0x303135)
  embed.set_thumbnail(url = user.avatar.url)
  embed.set_author(name = f'{user} ({user.id})', icon_url=user.avatar.url)
  
  embed.add_field(name = 'Joined:', value = f'<t:{int(joined)}:R>', inline=False)
  embed.add_field(name = 'Created:', value = f'<t:{int(creation)}:R>', inline=False)
  embed.add_field(name = 'Status:', value = f'{status}', inline=False)
  embed.add_field(name = 'Activity:', value = f'{user.activity}', inline=False)
  if len(user.roles) > 1:
    role_string = ' '.join([r.mention for r in user.roles][1:])
  embed.add_field(name="Roles:", value=role_string, inline=False)
  embed.set_footer(text = f'Join Position: {pos}')
     
  await ctx.send(embed=embed)```
cyan quail
#

this time it's ACTUALLY wrong order

#

you can see in your own command, if the user doesn't specify a user then user = None

peak wing
#

OHH

#

ok, this worked, ty @cyan quail

cyan quail
#

allgood

peak wing
# cyan quail allgood

my code is ```@client.command()
async def ui(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
status = user.status.name
bnnr = f'Banner'
if status == 'idle':
status = abcd
if status == 'offline':
status = abc
if status == 'online':
status = ab
if status == 'dnd':
status = a
pos = sum(m.joined_at < user.joined_at for m in ctx.guild.members if m.joined_at is not None)
joined = user.joined_at.timestamp()
creation = user.created_at.timestamp()

try:

embed = discord.Embed(description = f'{user.mention}', color=0x303135)
embed.set_thumbnail(url = user.avatar.url)
embed.set_author(name = f'{user} ({user.id})', icon_url=user.avatar.url)

embed.add_field(name = 'Joined:', value = f'<t:{int(joined)}:R>', inline=True)
embed.add_field(name = 'Created:', value = f'<t:{int(creation)}:R>', inline=True)
embed.add_field(name = 'Status:', value = f'{status}', inline=True)
embed.add_field(name = 'Links:', value = f'[Avatar]({user.avatar.url})\m{bnnr}', inline=True)
embed.add_field(name = 'Activity:', value = f'{user.activity}', inline=True)
if len(user.roles) > 1:
  role_string = ' '.join([r.mention for r in user.roles][1:])
embed.add_field(name="Roles:", value=role_string, inline=True)
embed.set_footer(text = f'Join Position: {pos}')
 
await ctx.send(embed=embed)

except AttributeError:
bnnr = 'No Banner'and i get the error:ands/core.py", line 193, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'

cyan quail
prisma flicker
#

well, it could be

#

but I guess both are important

peak wing
#

the avatar line isn’t the problem its the banner

cyan quail
#

oh true

#

fair enough then

simple canopy
#

is there display_banner

#

🤔

cyan quail
#

i don't think so...?

prisma flicker
cyan quail
#

oh right

#

you can only get banner from an api request

prisma flicker
cyan quail
#

hm

#

yeah

prisma flicker
#

await*

cyan quail
#

actually

#

no

simple canopy
#

@prisma flicker i mean, its kinda... banner?

cyan quail
#

client.fetch_user

#

i don't know if you can get the guild set banner

prisma flicker
peak wing
#

how can i fix.. my error?

cyan quail
#

maybe i'll test

simple canopy
prisma flicker
cyan quail
#

yeah you can't get it from fetch_member

#

odd that it isn't available

simple canopy
#

if only everything had default values...

prisma flicker
#

how is guild.fetch_member different from client.fetch_user

cyan quail
#

the former fetches a member object

prisma flicker
#

I feel like they should be the same

cyan quail
#

the latter fetches a generic user object

#

well not generic

simple canopy
cyan quail
#

but you can use it to fetch any discord user

prisma flicker
#

or guild.fetch_member should call fetch_user but add the guild stuff?

simple canopy
cyan quail
#

no, fetch_member is a different endpoint

prisma flicker
#

ah

simple canopy
#

i mean, fetch_member returns you member

#

and fetch_user a user

#

so ye, it just adds guild stuff probably

prisma flicker
#

well yes I get that

#

but I didn't realize they were different endpoints

peak wing
#

..

cyan quail
peak wing
simple canopy
cyan quail
#

though you're better off not including it since your command doesn't even fetch_user

#

so banner will always be None

undone falcon
#

I am running a big loop that takes a lot of time (a lot of iteration). I am currently doing at the end of each iteration of the loop await asyncio.sleep(0) to give the chance for the bot to take requests. Is there a better way to do it, because I sometime get error when user are doing slash command that the bot is not responding (the bot is using 100 % of the core it is assign because of that loop, the not responding probably comes from that)

#

I would want that loop to be executed in the "background"

prisma flicker
#

you can defer in your commands

undone falcon
#

I use defer in all my commands yes

prisma flicker
#

then you shouldn't ever see the not responding message

undone falcon
#

at some points it was apperaing often

prisma flicker
#

can you put the loop in a separate process that runs alongside your bot?

#

or break it up into pieces?

#

or only do a few iterations every minute?

undone falcon
prisma flicker
#

you can use locks

#

mutex/semaphore

undone falcon
#

that is true yes, I could probally look into that

#

thank you !

cyan quail
#

could you not use the tasks extension?

solemn spire
#

How do you use Options in slash commands?
What's wrong with this code because all of my slash commands disappeared

Option(
    discord.SlashCommandOptionType(),
    "your",
    required=False,
    default="Show",
    choices=[OptionChoice(name="Show"), OptionChoice(name="Adopt")]
)
prisma flicker
errant craneBOT
#

Here's the slash options example.

solemn spire
#

thanks

#

ok so

#

my slash commands reappeared for some reason

solemn spire
solemn spire
prisma flicker
#

why don't you just do choices=["Show","Adopt"]

solemn spire
#

I dont know

#

usually the more complicated stuff is better

prisma flicker
#

KISS

charred shale
#

What is the proper way to reference Pycord in a requirements.txt file?
I generated mine with pipreqs --encoding utf-8 "./"
This was the output:

discord.py==1.7.3
requests==2.28.1

When deploying the bot to PloxHost and running it, though, this error is generated:
AttributeError: module 'discord' has no attribute 'Bot'

(Note: The application runs perfectly fine on my local machine.)

smoky forge
prisma flicker
#

or py-cord==2.0.1

solemn spire
charred shale
#

Thank you both!

prisma flicker
solemn spire
#

the complete opposite lol

prisma flicker
#

what

solemn spire
#

store=True

prisma flicker
#

well that's the default

#

that returns a dict of errors instead of raising them

solemn spire
#

no errors

prisma flicker
#

how do you know? are you printing out the dict?

solemn spire
#

no

#

noithing

prisma flicker
#

then how can you say there's no errors

solemn spire
#

oh wait

#

module not found which is weird because its for another cog

#

and it worked before let me fix it quickly

#

what even is this
Extension 'app.cogs.pets' raised an error: TypeError: EnumMeta.__call__() missing 1 required positional argument: 'value'

prisma flicker
#

are you using enums in your pets cog

solemn spire
#

wait

#
File "d:\Desktop\peer\app\cogs\pets.py", line 20, in pets_cog
discord.SlashCommandOptionType(),
TypeError: EnumMeta.__call__() missing 1 required positional argument: 'value'
prisma flicker
#

idk what discord.SlashCommandOptionType is but it sounds like you have to pass in value to it

#

did you ReadTheDocs

cyan quail
#

(their usage is very wrong)

solemn spire
#

yes i did

#

its an input type

cyan quail
#

i guess it's not that bad but the first argument should just be a standard input type

#

like str

#

there's no reason to use discord.SlashCommandOptionType, it's just used internally

solemn spire
#

im using optionchoice tho

cyan quail
#

that's fine

solemn spire
#

oh

prisma flicker
#

you can literally just do like Option(str, "gender", description="Choose your gender", choices=["Male", "Female", "Other"])

#

you don't need any of that extra stuff

solemn spire
#

Omg it works

#

thank you so much

#

ima go sleep now

prisma flicker
#

good night and remember KISS 😛

naive remnant
#

Can I change the bot's avatar using a command?

errant craneBOT
#

Set your AFK: No reason specified.

rare ice
errant craneBOT
#

[AFK] RulzerFly. is AFK: No reason specified.

rare ice
#

oh for the love of-

naive remnant
#

H

#

@rare ice

naive remnant
naive remnant
#

Okay tnx

fiery tiger
#

basic_autocomplete seems like it doesn't work anymore? What changed

smoky forge
#

im sure basic autocomplete already does the startswith thing for you

prisma flicker
fiery tiger
#

bot

sweet tiger
#
@bot.event
async def on_message(message):
    print(enabled)
    if enabled == True:
        if message.guild.id in guildlist:
            if message.channel.id == 819570137555402822:
                if message.author.id not in blocklistnofds: 
                    uwutext = message.content

                    randomface = random.randint(0,1)
                    face = faces[randomface]

                    uwutext = (
                                uwutext.lower()
                                .replace("l", "w")
                                .replace("r", "w")
                                .replace("v", "f")
                                .replace("i", "i-i")
                                .replace("d", "d-d")
                                .replace("n", "n-n")
                                + face
                            )
                    await message.delete()

                    webhook = DiscordWebhook(url='WEBHOOK_URL', content=uwutext, username=message.author.display_name, avatar_url=message.author.avatar.url)

                    response = webhook.execute()

this is the error log i'm getting

Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "D:\Coding Stuff\Python\UwU Discord Bot\UwUifier.py", line 77, in on_message
    webhook = DiscordWebhook(url='WEBHOOK_URL', content=uwutext, username=message.author.display_name, avatar_url=message.author.avatar.url)
AttributeError: 'NoneType' object has no attribute 'url'
#

not sure what I'm doing wrong here :/

silver moat
#

The author probably doesn't have an icon

sweet tiger
#

it's me sending the message

peak wing
#
async def Stream():
    stream_labels = [f'in {len(bot.guilds)} guilds', '.help'] # sob
    await bot.change_presence(activity=discord.ActivityType.competing(name=random.choice(stream_labels)))

@bot.listen('on_ready')
async def Ready():
    os.system("cls;clear")
    print(f'''
[!] Loaded In {len(bot.guilds)} Guilds!
[!] Watching over {len(bot.users)} Users!
[!] Bot: {bot.user}
[!] Prefix: ;''')
    global startTime
    startTime = time.time()
    if not Stream.is_running():
        await Stream.start()``` ```Unhandled exception in internal background task 'Stream'.
Traceback (most recent call last):
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "main.py", line 17, in Stream
    await bot.change_presence(activity=discord.ActivityType.competing(name=random.choice(stream_labels)))
TypeError: '_EnumValue_ActivityType' object is not callable
Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 30, in Ready
    await Stream.start()
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 205, in _loop
    raise exc
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 176, in _loop
    await self.coro(*args, **kwargs)
  File "main.py", line 17, in Stream
    await bot.change_presence(activity=discord.ActivityType.competing(name=random.choice(stream_labels)))
TypeError: '_EnumValue_ActivityType' object is not callable``` how do  i fix this?
peak wing
silver moat
#

well, there's no await

#

also I'm assuming it's indented properly, right?

peak wing
#

i sent my code

silver moat
#

I'm on mobile

sweet tiger
#

is it possible for a bot.event to get message content? currently every message's content is just blank

silver moat
#

?tag message-content

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

sweet tiger
#

thanks

silver moat
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html

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)
silver moat
#

?tag edit intents
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.

obtuse juncoBOT
#

dynoSuccess tag intents edited.

peak wing
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'status'``` ```  @commands.command(aliases = ['whois', 'userinfo'])
  async def ui(ctx, user: discord.Member = None):
    if user == None:
      user = ctx.author
    status = user.status.name
    if status == 'idle':
      status = abcd
    if status == 'offline':
      status = abc
    if status == 'online':
      status = ab
    if status == 'dnd':
      status = a
    pos = sum(m.joined_at < user.joined_at for m in ctx.guild.members if m.joined_at is not None)
    joined = user.joined_at.timestamp()
    creation = user.created_at.timestamp()
  
    try:
    
      embed = discord.Embed(description = f'{user.mention}', color=0x303135)
      embed.set_thumbnail(url = user.avatar.url)
      embed.set_author(name = f'{user} ({user.id})', icon_url=user.avatar.url)
      
      embed.add_field(name = 'Joined:', value = f'<t:{int(joined)}:R>', inline=True)
      embed.add_field(name = 'Created:', value = f'<t:{int(creation)}:R>', inline=True)
      embed.add_field(name = 'Status:', value = f'{status}', inline=True)
      embed.add_field(name = 'Links:', value = f'[Avatar]({user.avatar.url})', inline=True)
      embed.add_field(name = 'Activity:', value = f'{user.activity}', inline=True)
      if len(user.roles) > 1:
        role_string = ' '.join([r.mention for r in user.roles][1:])
      embed.add_field(name="Roles:", value=role_string, inline=True)
      embed.set_footer(text = f'Join Position: {pos}')
       
      await ctx.send(embed=embed)
  
    except:
      print('a')``` what is this error im confused
silver moat
#

you are in a class

peak wing
#

oops

#

LOL

#

i just moved this over from my non cog folder

silver moat
#

all good

sweet tiger
#
D:\Coding Stuff\Python\UwU Discord Bot>py UwUifier.py
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1041, in on_connect
    await self.sync_commands()
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 643, in sync_commands
    registered_guild_commands[guild_id] = await self.register_commands(
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 472, in register_commands
    prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id)
  File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 354, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

uhhhhhh?

young bone
#

read the error ;3

sweet tiger
#

it appears it was missing access to something

#

thank you

young bone
near hollow
#

So @everyone is an option in discord.Roles. But when I try to mention the id of what it spits out it shows as @@everyone

silver moat
celest lichen
#

is there something i can add to my main.py that forces discord to update the slash commands it has registered for my bot on each deploy?

prisma flicker
celest lichen
#

i have an on_ready but no on_connect, could that still do it?

prisma flicker
#

maybe, just call super().on_ready()

celest lichen
#

wdym? after my normal on_ready?

#

this is my on_ready, btw

prisma flicker
#

yeah that's fine

#

so what problem are you having?

#

are you subclassing bot?

celest lichen
#

my problem is just that one of my slash commands isn't showing up when my bot is running lmao

prisma flicker
#

just one?

celest lichen
#

well honestly it's my only slash command

#

so i'm not sure

#

i'm using commands.Bot

orchid kernel
celest lichen
#

honestly i have no idea, i just have it at the end for neatness

#

ah there u go

round rivet
#

bot.run has to be at the end

#

because its blocking

celest lichen
#

yeah so

#

any ideas abt my slash command lol

prisma flicker
#

can you try @commands.slash_command() instead

orchid kernel
#

Given that my bot is using only slash commands, is it better to use @bot.slash_command instead of @bot.command? Or is it the exact same thing?

near hollow
#

if you are using discord.Bot it doesn't matter

orchid kernel
#

Yes I do

near hollow
#

Yea in that case bot.command is the same thing as bot.slash_command

prisma flicker
prisma flicker
near hollow
#

I thought they were on discord.Bot

#

Only commands.Bot support prefixed commands right?

prisma flicker
#

why did you delete your messages

orchid kernel
#

My screenshot was false

#

Need to verify myself before putting back my message

prisma flicker
#

👍

orchid kernel
#

Okay so yeah, I will switch for coherency and readability, since slash_command is formally in the documentation and that I only use this type of commands, otherwise it may be ambiguous

orchid kernel
prisma flicker
#

you're mixing context and command

orchid kernel
#

Yeah maybe, I'm not used to prefix commands so I don't know the syntax

prisma flicker
#

same 😄

fervent cradle
#

hello

#

i have an if else statement right

#

if x then post "success!" if y then post "fail"

#

the issue is that it doesn't post anything if it fails, not sure why

#

it just says "interaction failed"

prisma flicker
#

you have to respond

fervent cradle
#

but the "you are now whitelisted" works flawlessly

#

and im not sure why

prisma flicker
#

so what doesn't work?

fervent cradle
#

the text with a red box around it

#

i get this error

prisma flicker
#

you never edited the message, so you don't use followup

fervent cradle
#

gotcha

#

thank u so much

#

works, ty!

north tartan
#

I don't get the commands on the server

full basin
#

Reinvite your bot with application.commands scope

north tartan
#

oh, Ok thanks

north tartan
full basin
#

?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.

north tartan
#

I already invited it, I configured it and nothing the same error

#

now code: @bot.slash_command(guild_ids=[997349132974960690])

just change ids

prisma flicker
#

What permissions did you give the bot?

fervent cradle
#

did i instantiate it wrong or something

#

just copied the quickstart example on the homepage lol

round rivet
fervent cradle
#

it looks like supplying any arg to the prof function

#

causes that error

#

option parsing or otherwise

round rivet
#

try using = instead of typehinting

fervent cradle
#

evidenly i'm wrong though

#

dude what did i not set a default

#

LOL

#

i'm done

#

time for bed

#

although type hinting shoulda been fine

north tartan
prisma flicker
#

And what triggers the error? Just starting the bot?

spiral spruce
fervent cradle
#

2.0.1

north tartan
fervent cradle
#

how do i wait for a response to a select menu?

#

hang on i should read the docs before i ask that brb

#

oh yeah there's callbacks that's ezpz ty

prisma flicker
#

wait_for or callbacks

fervent cradle
#

is there a way to pass dynamic data when creating selects @prisma flicker?

#

decorators can't rlly take in vars unless i define the view class each time and nest it in a function

prisma flicker
#

You can create it without a decorator

knotty cipher
#

Is it possible to edit a persistent view(such as a button)?

night cargo
#

Is there a way to check how many times a member has boosted the server?

meager mica
#

hey guys recently bot.guilds has been returning empty list

#

has anyone had this issue

#

its on my cog load do i have to wait until ready

#

ok i fixed by removing from innit func

dreamy mauve
#

How to get user from username#discriminator?

inner heart
inner heart
#

The problem was I was trying to run the bot in another thread and didn't think it could cause any problems.

manic spoke
solemn spire
#

i'm currently using json to store data. I was thinking about switching to a something like SQLite. Is it really going to be faster? Every milisecond counts.

vale prism
#

how can I check if channel is a thread?

solemn spire
cyan quail
#

Do note they come with their own caveats so make sure you look into them too, e.g a common one is using string concatenation for queries which can leave you open to sql injection

frank yew
#

Why do I get this error?
AttributeError: 'TextChannel' object has no attribute 'news'

Code:

channel = await ctx.guild.get_channel(CHANNEL_ID)

        await ctx.defer()
        async for message in channel.history(before=date_limit_up, after=date_limit_down):
frank yew
cyan quail
#

Nope

frank yew
#

py-cord==2.0.0rc1?

cyan quail
#

We're on 2.0.1 now

frank yew
#

ouh

#

Sorry

cyan quail
#

That's a known bug from a previous version

#

All good

frank yew
cyan quail
#

If you use pip, just install py-cord again

real stirrup
#

wouldbot.on_message = onMessageEvent work

amber shale
#

how to unban a user (guild.unban need a member but how to get that?)

#

ok solved it 🙂

#

do i need to push time into db and check it every 10 minutes for unban in temporary bans?

smoky forge
#

if you need to store it in the db so it works after a restart

amber shale
#

ok

fervent cradle
#

From where i can get all the commands like ban , mute , kick all type

real stirrup
wise willow
#

Hey! What is the best practice for creating View? Creating class that inherits View or a functional approach (e.g. View.add_item())? Probably depends on the situation, but it's very interesting to hear an aside opinion.

celest lichen
#

this is a bit of a weird question but as an environment variable, what object should i store a database url as? this is postgres i'm talking about here

#

what i mean by this is

#

i'm trying to implement a database into my bot so i have some persistency on toggling commands on and off in different servers or channels

#

heroku stores the info for the psycopg2 connection in an environment variable called DATABASE_URL

#

i need my db to work locally as well for testing, but i feel like it would be way cleaner if i just had all that user="blaith", host="127.0.0.1" stuff in my .env file

#

but i'm not really sure what to store it as. a string? a list? a dict?

copper dew
solemn spire
#

i switched already

#

locking?

proud pagoda
#

How do I register a global before_invoke from within a Cog?

copper dew
# solemn spire locking?

I've had issues with SQLite locking up before, so I kinda stopped. I mainly use postgres instead. For your case, SQLite will probably work

cedar crystal
#

Can someone help me in my help post - upgrading help command to buttons

plucky meteor
#

Hello, I would like to know if I can limit the output of discord logging? or if not limit it to 100 characters so that there is not so much saturation

frank yew
#

how gets the message that a on_raw_reaction_add(payload)?

full basin
frank yew
#

But message = bot.get_message(payload.message_id) returns None 😦

full basin
#

Because on_raw triggers despite the chache

#

So the message is not cached

#

Wait for an answer God. Get some patience.

frank yew
full basin
#

fetch_message

frank yew
# full basin fetch_message

I do:message = await member.fetch_message(payload.message_id)

And I returns:
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

full basin
#

Do you realize what you're doing?

#

Read the docs

prisma flicker
frank yew
prisma flicker
frank yew
timber wedge
#

Is there an expiration time for a button once generated? It doesn't work over time

errant craneBOT
#

Here's the persistent example.

loud holly
#

I tried doing bot.mention to see if it works and it doesn't, is there any other way apart from doing

await ctx.respond(f"<@id>")
#

I want to mention the bot

#

nvm, I was adding in the wrong thing bot.user.mention

manic spoke
stray beacon
#

trying to generate a random number between 2 slash command options, error: ValueError: invalid literal for int() with base 10: ''

code:

async def gtn(ctx, min: discord.Option(int), max: discord.Option(int)):
    num = random.randint(min, max)
cedar crystal
#

Need help in in #1009461897659174942

manic spoke
#

Guys! I have some questions. Is it possible to create local slash commands? (Not global). Not for a specific guild. Also for what can you get message intent

prisma flicker
#

and your second question, are you asking what discord looks at for approving the intent?

peak wing
#
  async def ui(self, ctx, user: discord.Member = None):
    if user == None:
      user = ctx.author
    status = user.status.name
    activity = user.activity.name
    if activity = None:
      activity = 'None'
    if status == 'idle':
      status = abcd
    if status == 'offline':
      status = abc
    if status == 'online':
      status = ab
    if status == 'dnd':
      status = a
    pos = sum(m.joined_at < user.joined_at for m in ctx.guild.members if m.joined_at is not None)
    joined = user.joined_at.timestamp()
    creation = user.created_at.timestamp()

    embed = discord.Embed(description = f'{user.mention}', color=0x303135)
    embed.set_thumbnail(url = user.avatar.url)
    embed.set_author(name = f'{user} ({user.id})', icon_url=user.avatar.url)
      
    embed.add_field(name = 'Joined:', value = f'<t:{int(joined)}:R>', inline=True)
    embed.add_field(name = 'Created:', value = f'<t:{int(creation)}:R>', inline=True)
    embed.add_field(name = 'Status:', value = f'{status}', inline=True)
    embed.add_field(name = 'Links:', value = f'[Avatar]({user.avatar.url})', inline=True)
    embed.add_field(name = 'Activity:', value = f'{activity}', inline=True)
    if len(user.roles) > 1:
      role_string = ' '.join([r.mention for r in user.roles][1:])
    embed.add_field(name="Roles:", value=role_string, inline=True)
    embed.set_footer(text = f'Join Position: {pos}')
       
    await ctx.send(embed=embed)``` ```Traceback (most recent call last):
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/cog.py", line 718, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 839, in exec_module
  File "<frozen importlib._bootstrap_external>", line 976, in get_code
  File "<frozen importlib._bootstrap_external>", line 906, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/cogs/infos.py", line 28
    if activity = None:
                ^
SyntaxError: invalid syntax

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main.py", line 117, in <module>
    bot.load_extension(f'cogs.{cog}', store=False)
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/cog.py", line 838, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/runner/dvidvnijfdvindfnvifdnivfdnvdnvdfnivdfnvi/venv/lib/python3.8/site-packages/discord/cog.py", line 721, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.infos' raised an error: SyntaxError: invalid syntax (infos.py, line 28)
 ``` why wont this work?
fervent cradle
#

you dont compare to things with "=" you do that with "=="

manic spoke
manic spoke
manic spoke
fervent cradle
manic spoke
#

But hey can I “hide” slash

fervent cradle
#

i dont think so

young bone
manic spoke
#

Because I have 10 owner commands. They have different functionalities. One is for status, the other is for reloading extensions, the other stops the bot etc. I don’t want other people in my guild to see them. It’s easy to restrict them from using them, but I want to hide them

manic spoke
#

I think that’s a good reason for message intent to be given. Sometimes there are a lot of controls. And it’s easier to manage your app in the channel rather in terminal especially connecting through mobile phones

#

Also when is app directory launching 💀

peak wing
#
@commands.is_owner()
async def icon(ctx, role: discord.Role, emoji):
  await role.edit(icon=emoji)
  await ctx.send('set')```  does anyone know how i can do thing like set guild banners, role icons, etc
peak wing
smoky forge
#

im answering your question on how to set guild banners

peak wing
#
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all bytes, bytearray, and array.array objects, as well as many common memoryview objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.

Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include bytearray and a memoryview of a bytearray. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these include bytes and a memoryview of a bytes object.```
#

this isn't telling me what i need todo

smoky forge
#

if you wanna read from a file you have to convert it to bytes

meager mica
#

how do i have an option in a slash command only discord text channels

#

i can do in other libs but i cant figure out how in pycord

proud pagoda
#

Or you can use discord.Option and supply discord.TextChannel for the first arg

meager mica
#

oh thansk

proud pagoda
#

You're welcome

verbal dawn
#

'Member' object has no attribute 'avatar_url' any tips on fixing it?

somber remnant
#

hey, how to add a reaction to a response ? cause my bot say Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'add_reaction'

prisma flicker
#

you need to get the message from the interaction

#

so try interaction.message

somber remnant
#

well it say that interaction is not defined

#

cause i call it "message" bruh im dumb

#

It doesnt work :/

#

code :

      message = await ctx.respond(f"**YOU WILL DELETE __ALL__ DATA OF YOUR GAME , IT CANNOT BE UNDONE !**")

      await message.message.add_reaction("✅")
      await message.message.add_reaction("❌")

error : Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'

silver moat
somber remnant
#

but i use "message" everywhere in the code

simple canopy
#

💀

somber remnant
#

don't bully me cause i"m moving from basic to / commands

simple canopy
#

naming in interaction will help you in the future

#

also, im pretty sure, your IDE has tools to rename variables quickly

#

oh, yeah, VSC in not an IDE

somber remnant
#

yea but i really use message everywhere
and not only for this xd

somber remnant
simple canopy
#

don't be lazy

somber remnant
#

and i like reactions

peak wing
somber remnant
#

i prefere how reaction look like

simple canopy
#

i prefer how reactions were looking in 2019

somber remnant
#

so how i fix the problem

#

cause u just bully my variable name and my visual choice

simple canopy
#

🥴

#

interaction message's .message is None

somber remnant
#

yea, but only with add_reaction it doesnt work

simple canopy
#

try print(message.message)

somber remnant
#

kay

simple canopy
somber remnant
simple canopy
#

😱

young bone
#

you have to use original_message()

somber remnant
#

wdym ?

young bone
#

yes

simple canopy
#

yes

somber remnant
simple canopy
#

there is original_message() method inside of interaction message object

somber remnant
#

ho i see

#

wait a min i'll try

#

well hum

#

i dont understand how to use it

#

cause it's a couroutine

simple canopy
#

what do you do with courutines

somber remnant
#

u didnt explain me where i need to put it ;-;

#

i don't understand how to use it

#

it's just give me a couroutine

simple canopy
#

yes, because couroutines should be awaited

somber remnant
simple canopy
#

it will give you discord.Message object

#

im lying, InteractionMessage

#

and this one is basically discord.Message with interaction stuff, so any methods from discord.Message will work

somber remnant
#

I want to believe you but I still don't know what to do with it

simple canopy
#

🥴

somber remnant
#

;-;

simple canopy
somber remnant
#

message.orignal_message gave me <coroutine object Interaction.original_message at 0x000002D30673A500>

somber remnant
simple canopy
#

yes, because it was never awaited

#

i don't want to 🥄 feed you

somber remnant
#

yea ik

simple canopy
#

but im basically doing this rn

somber remnant
#

I DID IT

#

yay

#

that was hard

simple canopy
#

good job, now go learn about asynchronous code, and couroutines

somber remnant
#

now i have the same problem with clear reactions bruh

simple canopy
#

ultra pizdec imo

somber remnant
simple canopy
#

try figuring out it yourself

young bone
#

I need some popcorn

simple canopy
simple canopy
somber remnant
#

well ty for the help

#

ill try to resolve it myself tomorow

simple canopy
#

👍🏻

prisma flicker
frank thistle
#

If I have a list of unique floats, and a total, how do I most easily find the combination of floats from those lists which perfectly adds upto the total?

Example:
float list -> [[0.1, 0.2, 0.3], [0.33, 0.23, 0.12]]

I want to find the numbers from those lists which total 0.42 which would be 0.3 and 0.12

silver moat
#

of course you can brute force it. But first I have to ask you if this is homework or not

bright shard
#

id brute force it but i feel like theres a more elegant solution

bright shard
silver moat
#

¯_(ツ)_/¯

frank thistle
#

I was just gonna brute force it too, wanted to see if theres any better suggestions. Looked on stack overflow but I think im wording my problem wrong when I google it so im not getting the results im looking for after multiple rewordings

cyan quail
#

why are they even in separate lists

silver moat
#

I forgot what exactly but something in itertools is helpful

frank thistle
#

And i know, why not use a dict

cyan quail
#

i mean if the solution can use numbers from any list then you might as well just convert it to a single list

frank thistle
#

I dont know, I just didnt do it that way and now I dont want to change it xd

prisma flicker
#

If they're sorted you can make some optimizations

frank thistle
#

I cant combine them

#

So those lists of floats are the healing values from certain items in a game

#

Theres 3 of them because 2 of them are the healing value + a buff

#

So i have multiple lists for each item for each increment (level) of the buffs

bright shard
#

so youre basically trying to know what healing items to use to heal the exact amt of health you need?

frank thistle
#

No im trying to predict the healing items used when I only know the percentage gain of their health

prisma flicker
#

Sounds like no something you should let the user figure out

frank thistle
#

Each float is a percentage gain

prisma flicker
#

Oh...

frank thistle
#

Im doing this because that information isnt publicly available (the items they use)

#

But the amount their health is gained by is

cyan quail
#

what happens if there's multiple possible combinations?

prisma flicker
#

Why not just have the items used trigger a callback

bright shard
frank thistle
#

Just noticed I sent this in the wrong server (was supposed to be in Python lol)

#
{'Small First Aid Kit': [[0.05, 0.055, 0.06], [0.051, 0.056, 0.061], [0.052, 0.057, 0.062], [0.053, 0.058, 0.063], [0.054, 0.059, 0.064], [0.055, 0.06, 0.065], [0.056, 0.061, 0.066], [0.057, 0.062, 0.067], [0.058, 0.063, 0.068], [0.059, 0.064, 0.069], [0.06, 0.065, 0.07], [0.061, 0.066, 0.071], [0.062, 0.067, 0.072], [0.063, 0.068, 0.073], [0.064, 0.069, 0.074], [0.065, 0.07, 0.075]], 

'First Aid Kit': [[0.1, 0.11, 0.12], [0.102, 0.112, 0.122], [0.104, 0.114, 0.124], [0.106, 0.116, 0.126], [0.108, 0.118, 0.128], [0.11, 0.12, 0.13], [0.112, 0.122, 0.132], [0.114, 0.124, 0.134], [0.116, 0.126, 0.136], [0.118, 0.128, 0.138], [0.12, 0.13, 0.14], [0.122, 0.132, 0.142], [0.124, 0.134, 0.144], [0.126, 0.136, 0.146], [0.128, 0.138, 0.148], [0.13, 0.14, 0.15]], 

'Morphine': [[0.15, 0.165, 0.18], [0.153, 0.168, 0.183], [0.156, 0.171, 0.186], [0.159, 0.174, 0.189], [0.162, 0.177, 0.192], [0.165, 0.18, 0.195], [0.168, 0.183, 0.198], [0.171, 0.186, 0.201], [0.174, 0.189, 0.204], [0.177, 0.192, 0.207], [0.18, 0.195, 0.21], [0.183, 0.198, 0.213], [0.186, 0.201, 0.216], [0.189, 0.204, 0.219], [0.192, 0.207, 0.222], [0.195, 0.21, 0.225]], 

'Blood Bag': [[0.3, 0.33, 0.36], [0.306, 0.336, 0.366], [0.312, 0.342, 0.372], [0.318, 0.348, 0.378], [0.324, 0.354, 0.384], [0.33, 0.36, 0.39], [0.336, 0.366, 0.396], [0.342, 0.372, 0.402], [0.348, 0.378, 0.408], [0.354, 0.384, 0.414], [0.36, 0.39, 0.42], [0.366, 0.396, 0.426], [0.372, 0.402, 0.432], [0.378, 0.408, 0.438], [0.384, 0.414, 0.444], [0.39, 0.42, 0.45]]}
#

Anyway, heres all the lists and combos. It doesnt matter if theres multiple combinations across different items which total X.. however it does matter if theres multiple combinations to the same value in the same item which total X

cyan quail
#

like if you're trying to predict from a heal of 0.6 and your first pass uses 0.1 for the first item, restrict checks of the 2nd item to values around 0.5

frank thistle
#

Ok will do, might be a silly question but is there a better way to brute force than using a while loop and ensuring a result?

prisma flicker
#

Similar to what Nelo said, if each list is sorted, you can stop when you're too high or whatever

frank thistle
#

Yeah thats the plan, but if there is no result how do I know when its checked all possible combinations so it doesnt sit in an endless loop

cyan quail
#

nested for?

bright shard
#

i have an idea of how you could do that

cyan quail
#

would end itself

bright shard
#

im still new so forgive me if this is dumb but

frank thistle
#

Ive been doing python for years lol but this is something ive never tried

bright shard
#

could you take the first value in the list, iterate through the rest of the list seeing if first value + the value in the list is the answer?

prisma flicker
#

I think you can use set theory to solve it

frank thistle
#

I guess with enough time ill get it :p

frank thistle
bright shard
frank thistle
#

Yeah, its always a combination, never just a single

prisma flicker
frank thistle
#

Yes it is, in that case it just assumes the highest item (blood bag)

#

Thats all you can do in that situation

#

Actually no

prisma flicker
#

Or 6 small first aid kit

#

Or some other combination

frank thistle
#

No no, so you can see the amount of items used

#

And you can see the % health gained, you just cant see the items they used

cyan quail
#

fwiw this is NP-hard lol

prisma flicker
#

I feel like you've engineered a problem when there's a much easier solution

frank thistle
#

yeah probably

frank thistle
cyan quail
cyan quail
frank thistle
#

Alright ill try it, thanks a bunch lads

prisma flicker
#

So you can see "they used 3 items and healed 0.3"?

frank thistle
#

Yeah it doesnt say that but thats the parts I calculate

prisma flicker
#

Why can't you know the individual items used

frank thistle
#

Because thats just not what the game allows for

#

It would provide a competitive advantage

cyan quail
#

eh

frank thistle
#

And thats the advantage im trying to gain by making this kind of prediction / calculating system

prisma flicker
#

I don't get it but okay

cyan quail
#

if you really want, you could just precompute the values of every combination and have that saved as a dict

frank thistle
#

Yeah I could do that

cyan quail
#

the key being the total and the value being a list of the possible combinations

frank thistle
#

Thats a fuck ton of numbers hahah my brain is gonna be fried

prisma flicker
#

Or at the very least cache it in memory so it doesn't have to compute every single time

cyan quail
#

GuraShrug far, far less processing on the user's end though

#

yeah like

frank thistle
#

Yeah ill store it somewhere, once I can calculate them all

cyan quail
#

compute it all once when the bot starts

#

make it a dict

frank thistle
#

The number of combinations should never change (unless they add new items to heal)

#

So i can just store it permanently in json or smth

prisma flicker
#

You can cache it but not precompute everything, so the first time is slow

#

Easier to program 😛

cyan quail
frank thistle
#

Yeah thats a good idea, ill do that for the initial combinations too (that huge amount of floats)

#

Since its just being calculated each time its needed which is hella inefficient

cyan quail
#

do be careful with floating point accuracy though

#

might end up with some fun keys

frank thistle
#

I round them all to try avoid that

cyan quail
#

fair enough

frank thistle
#

Doesnt always work

#

sometimes even when rounding they come out like

#

0.13000000000000000003

cyan quail
#

maybe multiply them all enough to be ints?

frank thistle
#

When rounded to 3dp

cyan quail
#

then just round to 1

frank thistle
#

Might cause inaccuracies tho if it rounds up

rugged lantern
#

no it wont

frank thistle
#

prob best to just chop everything off after the 3rd dp

cyan quail
#

round to 3dp and multiply by 1000

#

close enough

frank thistle
#

yeah will do, thanks guys

#

I should be able to save some compute time, if its the first item in one of the float lists, it'll be the first item chosen in all of them

fiery tiger
#

How can i create a check using an url_regex. Checking if a message contains a link. For a purge command

            url_regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"

            def is_link():
                return url_regex
full basin
clever lake
#

Does anyone know what the longest length a custom invite url can be

clever lake
#

ty <3

dim flicker
#

Can I change the button by its custom_id? Example: ticket_status_button.button.label = "Ticket close"

#

I just want a certain button to change when I click on another button. Hahaha. And all of them are located in the 1st class.

orchid kernel
#

Hello, is there a proper way to shutdown a bot using a slash command?

silver moat
orchid kernel
#

Thank you!

#

Was wondering, do people usually use nodemon to run their bot?

peak wing
#
  File "main.py", line 2, in <module>
    from discord.ui import View
ImportError: cannot import name 'View' from 'discord.ui' (unknown location)``` i started randomly gettin this error?
rigid sable
#

Can someone send me an example of slash command choices in pycord?

errant craneBOT
#

Here's the slash options example.

errant craneBOT
#

Here's the slash basic example.

rigid sable
stuck kite
#

When setting up a group slash command in a cog, where is the best place to call the add application command line. I've followed the example in slash_cog_group.py and it doesn't include where to run the add applciation command line.

peak wing
#
  File "main.py", line 2, in <module>
    from discord.ui import View
ImportError: cannot import name 'View' from 'discord.ui' (unknown location)``` i started randomly gettin this error?
young bone
peak wing
young bone
#

you know basic python?

peak wing
# young bone you know basic python?
------------------ ---------
aiohttp            3.8.1
aiosignal          1.2.0
async-timeout      4.0.2
attrs              22.1.0
cachecontrol       0.12.11
cachy              0.3.0
certifi            2022.6.15
cffi               1.15.1
charset-normalizer 2.1.0
cleo               0.8.1
click              8.1.3
clikit             0.6.2
crashtest          0.3.1
cryptography       37.0.4
debugpy            1.6.2
distlib            0.3.5
filelock           3.7.1
flask              2.2.1
frozenlist         1.3.1
html5lib           1.1
idna               3.3
importlib-metadata 4.12.0
itsdangerous       2.1.2
jedi               0.18.1
jeepney            0.8.0
jinja2             3.1.2
keyring            23.7.0
lockfile           0.12.2
markupsafe         2.1.1
motor              3.0.0
msgpack            1.0.4
multidict          6.0.2
numpy              1.23.1
packaging          21.3
parso              0.8.3
pastel             0.2.1
pexpect            4.8.0
pip                21.1.1
pkginfo            1.8.3
platformdirs       2.5.2
pluggy             1.0.0
poetry             1.1.14
poetry-core        1.0.8
ptyprocess         0.7.0
py-cord            2.0.0
pycparser          2.21
pyflakes           2.4.0
pylev              1.4.0
pymongo            4.2.0
pyparsing          3.0.9
python-lsp-jsonrpc 1.0.0
python-lsp-server  1.5.0
pytoolconfig       1.2.2
replit             3.2.4
requests           2.28.1
requests-toolbelt  0.9.1
rope               1.3.0
secretstorage      3.3.2
setuptools         56.0.0
shellingham        1.4.0
six                1.16.0
tomli              2.0.1
tomlkit            0.11.1
typing-extensions  3.10.0.2
ujson              5.4.0
urllib3            1.26.11
virtualenv         20.16.2
webencodings       0.5.1
werkzeug           2.2.1
whatthepatch       1.0.2
yapf               0.32.0
yarl               1.8.1
zipp               3.8.1```
gentle flare
#

Hi I just startet making discord Bots and need help with an error.
Im using Pycord and want to make a Button.
But everytime I try to create one I get this error message ;

ModuleNotFoundError: No module named 'discord.ui'

I dont know how to fix this. In every Tutorial video I saw thy just used Pycord and did now Install anyhting other. And even in the official Docs they dont install anything other than Pycord. Does anyone know something?

prisma flicker
#

can you show me what you installed?

gentle flare
#

I installed py-cord like this : python3 -m pip install py-cord

#

Is there something other that I need to install

prisma flicker
#

and the line of code that's erroring?

gentle flare
#

I used the sample code from the Guide.

prisma flicker
#

can you send it

gentle flare
#
class View(discord.ui.View): # Create a class called View that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked

@bot.slash_command() # Create a slash command
async def button(ctx):
    await ctx.respond("This is a button!", view=View()) # Send a message with our View class that contains the button

prisma flicker
#

can you try this at the top of the file
from discord.ui import View
and change that to just class View(View)

gentle flare
#

ok now I works lol?

#

thx @prisma flicker

fervent cradle
#

which is the easiest database i can learn to integrate it with my discord bot?

simple canopy
#

sqlite i guess

fervent cradle
#

alr thx

smoky forge
#

e.g. aiosqlite, aiomysql, asyncpg

somber remnant
#

Hey, why the cog check doesnt work on / commands ? there is a way to fix that ?

#

plz ping me if you have an answer prayadge

solid agate
#

Can I auto populate a select dropdown with GuildChannel?

gentle flare
#

Hey I need to update my Python version on my server. I already Installed Python3.9.13 and I alredy deleted my previous python version ( python3.6.9 ) But I still find folders in the /etc directory and its still there when I do python3 -V . Does anyone know what to do?

naive remnant
#

How do I make only admins can Acess a command

dim flicker
#

Guys, can I declare embed with a variable in 1 file and then import it into another and use it?

#

Just how do I declare these variables in an embed file? Because they will be highlighted in red. Can I just import them(variables)?

gentle flare
#

Hey how do I get the id of the one using a button?

full basin
#

Imports are basic python.

dim flicker
#

Well, I figured it out. Well okay. It's hard for me to explain in English.

fervent cradle
prisma flicker
#

I don't understand your question, where is this output?

#

please elaborate

#

this will give you the folder name of the file you're in
os.path.dirname(os.path.realpath(__file__))

fervent cradle
#

Hey how do I make the bot show bot is thinking... on a slash cmd?

simple canopy
fervent cradle
fervent cradle
#

ty

gilded barn
#

heyo, can someone link me to the docs of the dropdown menu feature

gilded barn
#

hey thanks dude!

gentle flare
#

Hey I have a working module and it does what it should do but I get an error message when I submit.

class createOpenTicketMenu(Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(timeout=None,*args, **kwargs)

        self.add_item(discord.ui.InputText(label="Describe you problem:", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):

        embed = discord.Embed(color = discord.Color.blue(), title="Open Ticket")
        embed.set_author(
            name        = interaction.user.display_name, 
            icon_url    = interaction.user.display_avatar
            )
        embed.add_field(name="Problem:", value=self.children[0].value)

        overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            interaction.user: discord.PermissionOverwrite(read_messages=True, read_message_history=True, send_messages=True)
        }
        ticket = await interaction.guild.create_text_channel(f'ticket-{interaction.user.display_name}', overwrites=overwrites)

        await ticket.send_message(embeds=[embed])

Still it works. I dont know whats wrong but I dont get a error message in the console.

prisma flicker
gentle flare
#

can you give me an example pls

prisma flicker
gentle flare
#

ah so it needs to give a "respond" or what does it mean?

prisma flicker
#

you must respond to every interaction

#

slash commands, buttons, modals

gentle flare
#

ah ok thx. That helped me alot

prisma flicker
#

that response can be sending a message or editing the message

gentle flare
#

^^

somber remnant
#

hello, how i can use "cog" parameter for my slash commands ? i don't understantd

prisma flicker
#

self is your cog

somber remnant
#

okay but it say that it's not defined

naive remnant
#

How can I make a error handler for missing arguments

empty tree
fervent cradle
#
   @slash_command(name='poll', description='Creates a poll')
    async def poll(
    self,
    ctx: discord.ApplicationContext,
    title,
    option1: discord.Option(
        str, 'Enter Option One',
        Required=True
         )):
       await ctx.respond(title,option1)``` Hey, Im trying to make a poll command but the bot isnt responding no error in teminal
proud pagoda
fervent cradle
#

@proud pagoda

neon raven
#

How do I run background Task? Any dummy code?

prisma flicker
somber remnant
#

i will send it

somber remnant
# prisma flicker are you not in a class? it's hard to guess what's wrong without seeing your code


def setup(bot):
    bot.add_cog(GameChar(bot))


class GameChar(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def cog_check(self, ctx):
        return ctx.guild != None and ctx.channel.guild.me.guild_permissions.administrator == True and kc.paused == False



    @discord.slash_command(name="cl",description="Characters list - Display the Selen characters list")
    async def characterslist(self, ctx,sort_option : discord.Option(str,description=("Choose how the characters will be sorted"),choices=[discord.OptionChoice(name="Sort by id",value="id"),discord.OptionChoice(name="Sort by rarity",value="r")],required=False,default=None)):```
#

This is the beggining of my cog (without import)

#

and i want to use cog parameter in this fonction

prisma flicker
somber remnant
#

I've probably misdefined it, but I'm stupid, that's normal.

prisma flicker
somber remnant
#

but i add it at the end of the options

#

after default

prisma flicker
#

why would you remove it when trying to show me what's wrong?

fervent cradle
prisma flicker
#

you should just use self in your code

somber remnant
#
async def characterslist(self, ctx,sort_option : discord.Option(str,description=("Choose how the characters will be sorted"),choices=[discord.OptionChoice(name="Sort by id",value="id"),discord.OptionChoice(name="Sort by rarity",value="r")],required=False,default=None,cog=self)):
prisma flicker
fervent cradle
prisma flicker
somber remnant
#

wdym ? before async def ?

prisma flicker
#
async def characterslist(self, ctx,sort_option : discord.Option(str,description=("Choose how the characters will be sorted"),choices=[discord.OptionChoice(name="Sort by id",value="id"),discord.OptionChoice(name="Sort by rarity",value="r")],required=False,default=None)):
    cog=self
fervent cradle
# fervent cradle Alright, will try it

Traceback (most recent call last):
File "C:\Users\jackd\Documents\FelBot\main.py", line 21, in <module>
bot.load_extension(f"{directory[2:]}.{filename[:-3]}",store=False)
TypeError: CogMixin.load_extension() got an unexpected keyword argument 'store'

did i put this in the wrong place?

somber remnant
#

sry if i look stupid but i don't understand much about / commands

fervent cradle
#

I have this issue on v2.0.1

class B1(Button):
    def __init__(self):
        super().__init__(label="Test B")
    async def callback(self, interaction):
        embed=discord.Embed(title="User Identification", description="BBB", color=33023)
        await interaction.response.edit_message(embed=embed)
class B2(Button):
    def __init__(self):
        super().__init__(label="Test C")
    async def callback(self, interaction):
        embed=discord.Embed(title="User Identification", description="CCC", color=33023)
        await interaction.response.edit_message(embed=embed)
buttons_ui = B1()
buttons_ui2 = B2()
view_ui_buttons = View()
view_ui_buttons.add_item(buttons_ui)
view_ui_buttons.add_item(buttons_ui2)
embed=discord.Embed(title="User Identification", description="AAA", color=33023)
await channel.send(embed=embed, view=view_ui_buttons)

When pressing any of the buttons it just says "This interaction failed", any fix??
No error appears on console.

prisma flicker
fervent cradle
#

Whats the command to update?

prisma flicker
#

same command you ran to install

#

I think -U on pip will upgrade

fervent cradle
#

Alr

somber remnant
#

it work, but the cog check doesnt apply

fervent cradle
#

can anyone help me with the discord.ui.button callback??
trying to fix since yesterday

somber remnant
#

i want that my cog check work on my / commands

prisma flicker
#

what is "cog check"

fervent cradle
somber remnant
#

    async def cog_check(self, ctx):
        return ctx.guild != None and ctx.channel.guild.me.guild_permissions.administrator == True and kc.paused == False

#

that will check every commands before go in the code, and return an error if condition are false
But it doesnt work with / commands

prisma flicker
somber remnant
#

its an import

prisma flicker
fervent cradle
prisma flicker
prisma flicker
somber remnant
fervent cradle
fervent cradle
#

Updated and stuff, no error but still no response

prisma flicker
fervent cradle
#

cant, dont have nitro

prisma flicker
fervent cradle
prisma flicker
#

?tag paste

obtuse juncoBOT
fervent cradle
#

either works ^

somber remnant
somber remnant
prisma flicker
somber remnant
#

well ill make something who works like cog_check, too lazy to change every commands

prisma flicker
#

I know you can do custom checks but I forget the exact syntax

somber remnant
#

thx for the help

cyan quail
#

you're looking for bot_check

fervent cradle
somber remnant
cyan quail
#

cog_check will also work yes

#

bot_check is for the entire bot, cog_check is for the current cog

somber remnant
#

but it didnt work with my / commands

#

yea ik

cyan quail
#

are you sure? cogs were reworked to be a part of the core bot which is slash based

fervent cradle
#

u just leaked it

somber remnant
fervent cradle
#

Make sure to always remove your token, or use a .env

prisma flicker
fervent cradle
prisma flicker
#

combine them into one string if you want but don't pass in 2 options to respond

fervent cradle
prisma flicker
#

sure you can make an embed, or just make one string

prisma flicker
fervent cradle
fervent cradle
prisma flicker
#

subclass View and add the buttons there

fervent cradle
prisma flicker
#

you can do:

ctx.respond(mystring)
ctx.respond(mystring, embed=myembed)
ctx.respond(embed=myembed)
ctx.respond(embed=myembed,view=myview)
ctx.respond(mystring,view=myview)``` etc but only one arg, the rest should be kwargs
somber remnant
# cyan quail are you sure? cogs were reworked to be a part of the core bot which is slash bas...

    async def cog_check(self, ctx):
        return ctx.guild != None and ctx.channel.guild.me.guild_permissions.administrator == True and kc.paused == False


#Liste generale + commande pour voir tout les Spersos
    @discord.slash_command(name="cl",description="Characters list - Display the Selen characters list")
    async def characterslist(self, ctx,sort_option : discord.Option(str,description=("Choose how the characters will be sorted"),choices=[discord.OptionChoice(name="Sort by id",value="id"),discord.OptionChoice(name="Sort by rarity",value="r")],required=False,default=None)):```
#

here, my bot doesnt have the permissions

fervent cradle
fervent cradle
#

Should i use 2 ctx.responds

prisma flicker
#

no, you can't

prisma flicker
fervent cradle
prisma flicker
fervent cradle
#

might as well use embed rn, right

fervent cradle
prisma flicker
#

we can use your thread

#

#1009857397243793418

fervent cradle
#

alr

proud mason
#

i want to check if any item from List1 is in List2
what is better?

check = any(item in List1 for item in List2)

or converting those lists to sets and using set intersection

cyan quail
somber remnant
cyan quail
#

from the looks of it bot_check should work fine, but i don't think cog_check was implemented in can_run

fervent cradle
#

    @slash_command(name='poll', description='Creates a poll')
    async def poll(
    self,
    ctx: discord.ApplicationContext,
    title,
    option1: discord.Option(
        str, 'Enter Option One',
        Required=True
         )):
        Poll = discord.Embed(title=title, description=option1)
        await ctx.respond(Poll)```  It just returns, <discord.embeds.Embed object at 0x000001772ADEC5E0>
#

Might be missing something? dunno

prisma flicker
#

also your variables should be lowercase... so just poll

#

or poll_embed

fervent cradle
#

Works now, Thanks!

prisma flicker
#

oh?

fervent cradle
#
poll = discord.Embed(title=title,description=':thumbsup:', option1 )```, Positional argument cannot appear after keyword arguments

Why do i get this? and i cant add it like 
description=option1, option2
prisma flicker
#

I don't know what you're trying to do. but try this?
poll = discord.Embed(title=title,description=f':thumbsup:\n{option1}' )

simple canopy
prisma flicker
#

or

poll = discord.Embed(title=title,description=':thumbsup:' )
ctx.respond(option1,embed=poll)
fervent cradle
simple canopy
#

you should try

#

i'm pretty sure it will, i just felt like saying what's actually wrong would be nice

prisma flicker
#

there's lots of ways to present the information, and I don't know how you want it presented

#

but like giga said, you can't just throw commas into function calls and expect it to work 😄

fervent cradle
#

My bad, Im a little rusty xD

#
option2: discord.Option(
        str, 'Enter Option Two', 
        required=False ) = 'No Option'):``` How would i just make it respond with litearly nothing? instead of no option if theres no input there
#

Sorry im asking a lot

#

(I do attempt to fix these myself, just struggling)

prisma flicker
#

you have to respond to the slash command

fervent cradle
#

Nevermind lol

#

My bad, just had to have empty quotes

fervent cradle
#

Bro, Am i stupid? Hows this needing an indentation? It seems all the right indentations & if i indent it, it messes the rest up

somber remnant
#

you put : at the end of option1 parameter

#

just before option2

#

instead of a ,

cyan quail
errant craneBOT
somber remnant
#

well, i can't rn but tomorow i'll probably ask for this

#

ho okay i have to edit core file

#

well that's not too hard for me i guess

fervent cradle
somber remnant
#

u forgot the , between option 1 and 2

#

and your ) are not at the good location

#

i think

young bone
simple canopy
#

use Refactor Code ah, yes, VSC

somber remnant
#

if you want to use a default value, do default="No options..." in the options

somber remnant
simple canopy
#

👍🏻

somber remnant
#

now i can copy and paste understand what i'm doing

#

well that's not really hard when u did it one time

wintry shell
#

yo nerfd

#

nerd

#
import pyautogui

pyautogui.moveTo(208, 1036)
pyautogui.click()
pfp = pyautogui.locateOnScreen("AltGenPFP.png", confidence = 0.8)
pyautogui.moveTo(pfp)
pyautogui.click()
#

why does it not go to the pfp and click

clever lake
#

guessing theres no way to force autocomplete to require an answer from the array u pass it

simple canopy
wintry shell
#

what are you guys saying

clever lake
#

its a p chonky array

#

sorry the question was badly phrased

wintry shell
#

is this abouy my script

clever lake
#

nonono

#

sorry 😅

wintry shell
#

i will commit arson

clever lake
fervent cradle
clever lake
#

is ur setup in ur cog class?
if so it shouldnt be

simple canopy
wintry shell
#

what

fervent cradle
# clever lake is ur setup in ur cog class? if so it shouldnt be
from multiprocessing.sharedctypes import Value
import discord
from discord.commands import slash_command
from discord.ext import commands

class PollCr(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command(name='poll', description='Creates a poll')
    async def poll(
    self,
    ctx: discord.ApplicationContext,
    title,
    option1: discord.Option(
        str, 'Enter Option One', 
        required=False ) = 'No Option Given',
    option2: discord.Option(
        str, 'Enter Option Two',
        required=False ) = 'No Option Given'
    poll = discord.Embed(title=title,description=f':thumbsup: {option1} \n\n:thumbsdown: {option2} ' )
    await ctx.respond(embed=poll)
def setup(bot):
    bot.add_cog(PollCr(bot))
``` Dont think so, if so how can i fix this? Would i have to intent my class?
fervent cradle
# wintry shell what

This is the pycord help channel as said, Not for support about non pycord related code

simple canopy
#

bruhy bruh

fervent cradle
simple canopy
#

.gg/python <-

fervent cradle
#

rip giga

wintry shell
fervent cradle
clever lake
fervent cradle
clever lake
#

to create bots

simple canopy
fervent cradle
#

How did you mistake pycord with python 💀

wintry shell
clever lake
#

yeee

clever lake
#

except dyno doesnt use pycord

#

but v similar

wintry shell
#

like luacord

fervent cradle
wintry shell
#

fortcord

simple canopy
#

why the f*ck am i banned from python discord

#

💀

clever lake
#

lol

prisma flicker
wintry shell
wintry shell
wintry shell
#

i remmeber you

prisma flicker
simple canopy
fervent cradle
#

Oh my bad

simple canopy
simple canopy
#

? peepoBlink

prisma flicker
simple canopy
#

ah mmLol

#

next is 22222 😎

prisma flicker
#

that's gonna take a while

simple canopy
#

about a 1-1,5 months i think

wintry shell
#

how do i make bot scroll down

#

cus im also banned in python server

prisma flicker
#

scroll down?

wintry shell
prisma flicker
#

I don't understand

wintry shell
#

like pyautogui.click() makes you click

#

what do u need to do to scroll

prisma flicker
#

it's probably in the docs for pyautogui

fiery tiger
#
            if not before.is_news() and after.is_news():
                before_type = before.type
                await after.guild.ban(i.user, reason="Anti-Nuke: Changing channel announcement")
                await after.edit(type=before_type)

            if before.is_news() and not after.is_news():
                before_type = before.type
                await after.guild.ban(i.user, reason="Anti-Nuke: Changing channel announcement")
                await after.edit(type=before_type)
#

Why is the bool is_news() not working? it should be colored in yellow

#

could it be because i have to check the isinstance? to make sure its a text channel?

#

but if i do that it could affect the other code

#

entire code for channel update

wintry shell
#

how do i write $ with python

fiery tiger
#

nvm i got it.

proud pagoda
fiery tiger
#
    @commands.Cog.listener()
    async def on_guild_role_update(self, before, after):
        print("update")

        # HANDLER NEEDED TO CHECK IF MEMBER IS WHITELISTED

        if before.guild.me.guild_permissions.view_audit_log != True:
            print("checking this")
            return

        async for i in after.guild.audit_logs(
            limit=1,
            after=datetime.datetime.now() - datetime.timedelta(minutes=1),
            action=discord.AuditLogAction.role_update
        ):

            if i.guild.me.guild_permissions.manage_roles != True:
                print("checking this too")
                return

            # if i.user.id == i.guild.owner.id:
            #     return

            # if i.user.id == i.guild.me.id:
            #     return

            # if i.user.top_role >= i.guild.me.top_role:
            #     return
            print("reached here")
            if before.name != after.name:
                print("check1")
                before_name = before.name
                # await after.guild.ban(i.user, reason="Anti-Nuke: Changed role name")
                await after.edit(name=before_name)
#

my output will print just
update
reached here

#

i just can't tell why it doesn't go over that + why it doesn't print the other checks?

#

nvm. Found out

obtuse juncoBOT
prisma flicker
# fiery tiger

wait this works?
if i.user.top_role >= i.guild.me.top_role:

fiery tiger
fiery tiger
prisma flicker
rigid sable
#

Why is this giving an error?

prisma flicker
fiery tiger
#

lol

rigid sable
#

it says all the strings are undefined

prisma flicker
rare ice
rigid sable
#

but I'll update you when I can run it

rare ice
#

?tag norepl

#

@obtuse junco

rigid sable
#

whole reason I use pycord is cause repl supports it lol

rare ice
#

Don’t use replit it’s not recommended and it’s a very unstable host.

rigid sable
#

ok

prisma flicker
#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

rare ice
#

dyno hates me

prisma flicker
#

replit supports any python lib, you just have to set up the configs right

rigid sable
#

What exactly does this mean?

smoky forge
#

a single host can have many files running at once

#

if one gets rate limited it means the rest will

rigid sable
#

Ok

rigid sable
fervent cradle
#

how can I use this variable inside the subclass?
UnboundLocalError: local variable 'test1' referenced before assignment

test1 = None
test2 = None
confirmations = []

class V1(View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="I am tester1", custom_id='buyer_b')
    async def button1_callback(self, button, interaction):
        if test1 == interaction.user:
            test1 = None
        test2 = interaction.user
        embed=discord.Embed(title="User Identification", description="Done! 1", color=33023)
        await interaction.response.edit_message(embed=embed)
    
    @discord.ui.button(label="I am tester2", custom_id='seller_b')
    async def button2_callback(self, button, interaction):
        if test2 == interaction.user:
            test2 = None
        test1 = interaction.user
        embed=discord.Embed(title="User Identification", description="Done! 2", color=33023)
        await interaction.response.edit_message(embed=embed)

view_ui_buttons = V1()
embed=discord.Embed(title="User Identification", description="AAA", color=33023)
await channel.send(embed=embed, view=view_ui_buttons)
full basin
#

Set it as a class attribute?

fervent cradle
#

on the init?

#

to access it from outside the class I use view_ui_buttons.attribute ?

#

long time without using python i forgot

full basin
#

Inside a class, the class is referenced with self

#

?tag lp

obtuse juncoBOT
#
fervent cradle
#

yea i did that

full basin
#

Then?...

fervent cradle
#

worked just need to make sure if view_ui_buttons.attribute_name is correct or not

#

ill check docs

full basin
#

Depends

fervent cradle
#
confirmations = []

class V1(View):
    def __init__(self):
        super().__init__()
        self.test1 = None
        self.test2 = None

    @discord.ui.button(label="I am tester1", custom_id='buyer_b')
    async def button1_callback(self, button, interaction):
        if self.test1 == interaction.user:
            self.test1 = None
        self.test2 = interaction.user
        embed=discord.Embed(title="User Identification", description="Done! 1", color=33023)
        await interaction.response.edit_message(embed=embed)
    
    @discord.ui.button(label="I am tester2", custom_id='seller_b')
    async def button2_callback(self, button, interaction):
        if self.test2 == interaction.user:
            self.test2 = None
        self.test1 = interaction.user
        embed=discord.Embed(title="User Identification", description="Done! 2", color=33023)
        await interaction.response.edit_message(embed=embed)

view_ui_buttons = V1()
embed=discord.Embed(title="User Identification", description="AAA", color=33023)
await channel.send(embed=embed, view=view_ui_buttons)
while test2 == None or test1 == None:
  wait(1)
await channel.send("Both testers verified!")

any ideas on how to wait for both to get confirmed without breaking the discord buttons?

#

the while: wait() line breaks the buttons

wintry shell
#

how do i print("$bro nah")

#

it doesnt print the $

full basin
fervent cradle
#

i mean

#

i need to wait for each person to press a button

cyan quail
#

how about

fervent cradle
full basin
#

Can't you continue? Isn't that a keyword for while loops

cyan quail
#

you just shouldn't use while lol

#

that'll block your entire bot

full basin
#

Are while loops even good for async

fervent cradle
#

hmmm

fervent cradle
full basin
#

My thought was right

fervent cradle
#

wait wtf im using wait instead of time.sleep isn't that the problem?

cyan quail
#

both of those would suck

full basin
#

That was what I was thinking.

fervent cradle
#

yes but i need to check each person and also if one of them missclickes they should be able to click the right one

cyan quail
#

that's not too hard is it

full basin
#

That's just an if statement

#

Before running view.stop

cyan quail
#

also note view.wait() will return True if it timed out naturally, and False if it was stopped; you should use this to verify if it was actually pressed or the view ran out of time

fervent cradle
#

my head hurts
basically my client wants the view to persist

full basin
#

How's that a problem

errant craneBOT
#

Here's the persistent example.

fervent cradle
#

well

#

the buttons cant be disabled and the buttons cant disappear

#

so if i do view.stop()

cyan quail
#

that's the default behavior...

#

hm

full basin
#

Wdym you can't disable them