#Basic Pycord Help (Quick Questions Only)

1 messages · Page 8 of 1

slim drum
#

how can i use rgb values?

copper dew
#

I mean randint works best for rgb values

frank yew
#

How can I get all messages in a channel?

slim drum
#

i also tried to use a specific color but that didnt seem to work either

copper dew
slim drum
#

tysm!! ill try it and update you

copper dew
slim drum
#

hm, still shows no color @copper dew

#
    @bridge.bridge_command(name = ["avatar", "av"], description = "Get a user's avatar!")
    async def av(self, ctx, user: discord.Member = None):
      
     if user == None: 
      user = ctx.author
    
     embed = discord.Embed(description = f"{user.name}\'s avatar", color=discord.color.from_rgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
     embed.set_image(url=user.display_avatar.url)
     await ctx.respond(embed=embed)
outer obsidian
slim drum
#

yup

outer obsidian
outer obsidian
slim drum
#

ah tyty

slim drum
# outer obsidian you can instead use `discord.Color.random()`

still :( it isnt working:

import discord
from discord.ext import bridge, commands
import random


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

    @bridge.bridge_command(name = ["avatar", "av"], description = "Get a user's avatar!")
    async def av(self, ctx, user: discord.Member = None):
      
     if user == None: 
      user = ctx.author
    
     embed = discord.Embed(description = f"{user.name}\'s avatar", color=discord.Color.random())
     embed.set_image(url=user.display_avatar.url)
     await ctx.respond(embed=embed)
     
def setup(bot):
    bot.add_cog(General(bot))
#

image is the current default color of embeds

#

i even used noelle's random rgb code (with capital C) and it still didnt work

#

im really confused on why this isnt working seeing how it works perfectly fine in my ping command

slim drum
#

/ping has random colors yet /avatar does not

#

@copper dew @outer obsidian update: i fixed it but now the command cog doesnt even show up anymore (typing /avatar doesnt show anything). the code i use to actually load the cogs is here :

cogfiles = [ f"cogs.{filename[:-3]}" for filename in os.listdir("./cogs") if filename.endswith(".py")]

for cogfile in cogfiles:
  try:
    bot.load_extension(cogfile)
  except Exception as err:
    print(err)

I put this in main.py

fervent cradle
#

How can i ignor bot message in on_message event

halcyon helm
#
If message.author.bot:
    return
slim drum
# outer obsidian any errors?

nope, it does show anything except when i actually try the command (using a prefix since its a hybrid) telling me that the command doesnt exist

#

if it helps:

#

main.py

import discord
import os
from discord.ext import bridge
import random
import logging

#Logging system
logging.basicConfig(level=logging.INFO)

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

bot = bridge.Bot(command_prefix = ["miko", "m?"], intents=intents, debug_guilds = [866257158692929536])

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.bridge_command(name = "ping", description = "A simple ping command.")
async def ping(ctx):
  embed = discord.Embed(title = "Miko Bot's latency!",
    description = f"Pong! I'm running at about {round(bot.latency * 1000)} ms.", color=random.randint(0, 0xFFFFFF))
  await ctx.respond(embed=embed)

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        bot.load_extension(f"cogs.{filename[:-3]}")


  
my_secret = os.environ['TOKEN']
bot.run(my_secret)

/cogs/general.py

import discord
from discord.ext import bridge, commands
import random

class General(discord.Cog):
    def __init__(self, bot):
        self.bot = bot

    @bridge.bridge_command(name = ["avatar", "av"], description = "Get a user's avatar!")
    async def av(self, ctx, user: discord.Member = None):
      
     if user == None: 
      user = ctx.author
    
     embed = discord.Embed(description = f"{user.name}\'s avatar", color=discord.Color.random())
     embed.set_image(url=user.display_avatar.url)
     await ctx.respond(embed=embed)
     
def setup(bot):  
  bot.add_cog(General(bot))
#

thats all of my code till now

outer obsidian
#

ok

slim drum
#

i really cant see any problems with it but the cog still doesnt show up

outer obsidian
#

hmm i dont see anything wrong

simple canopy
#

try printing out the list you are getting in your cog loader

outer obsidian
simple canopy
#

may be there is something you'll need to replace and/or change

slim drum
#

btw i use class General(commands.Cog): and not (discord.Cog) if that changes anything

outer obsidian
#

it wont change anything i believe

outer obsidian
slim drum
#

okay

#

nothing

outer obsidian
#

hm

simple canopy
slim drum
#

im using replit if that changes anything

outer obsidian
#

then meaning that the cog isnt loading.... you could try manually loading the cog and see if there is errors or smth

civic jayBOT
simple canopy
slim drum
#

how do i manually load it?

outer obsidian
slim drum
outer obsidian
slim drum
#

it does list it

outer obsidian
#

but it isn't loading... breh

slim drum
#

this is the only command that shows up

simple canopy
#

try printing out info after bot load extension

#

actually, does legacy command work?

#

you are using bridge, so try running {prefix}av

#

it may be an issue with bridge

slim drum
#

same result

simple canopy
outer obsidian
#

welp

slim drum
#

maybe its a replit problem, ill run my code using visual studio code and see if it works

outer obsidian
#

reverting changes might fix your problem...

slim drum
#

@outer obsidian @simple canopy the response i get from VSC

outer obsidian
#

it must be a string

#

for example:
name='avatar'

simple canopy
#

AH OMG

slim drum
#

ohhh!!!

outer obsidian
#

you can only have list on aliases

outer obsidian
simple canopy
#

FUCK IM STUPID, I SAW IT AND DIDN'T EVEN NOTICE

slim drum
#

im so stupid lmfaoo FalseFacePalmLaughFalseFacePalmLaugh

#

im sorry for troubling you all

outer obsidian
#

i tot it was aliases

simple canopy
#

slashes can't have aliases

slim drum
#

aaahh okay

outer obsidian
slim drum
simple canopy
#

not sure, i use only slash

outer obsidian
#

i dont use bridge, i use only slash or only prefixed lmao

slim drum
#

this should work right?

outer obsidian
#

yep

slim drum
#

WOO it does work !!!

#

tyty everyone <33 wowcry

outer obsidian
#

np

fervent cradle
#

How can i ignor bot message in on_message event

simple canopy
#

yes you can

#

use message.author.bot

#

its boolean

fervent cradle
cyan quail
simple canopy
slim drum
cyan quail
#

yes

#

now errors will actually raise if there's anything wrong when loading the cog

fading granite
#

how do you pass environmental variables from github to your code?

#

I've tried this

#

And i'm using Railway to host my bot, this error appears when running

#

i basically have no idea how to pass environmental variables in github without an env file

celest lichen
#

can anyone figure out why this isn't working?

#

the bot logs in - my @bot.event works perfectly. but the prefixed command just does not do anything

#

i cannot for the life of me figure it out

full basin
#

You're defining your command as (ctx, arg), so if you're running the command without providing any argument it should raise an error.

celest lichen
#

oh sorry the arg thing is left over from me trying something else with that command

#

it hasn't actually been in any of the other times i've ran the command haha

young bone
#

you need ctx.send or ctx.reply

celest lichen
#

swapped it to ctx.reply and still nothing

#

i think i swapped it to ctx.respond when i tried changing @bot.command() to @bot.slash_command

young bone
#

add to the arg =None

celest lichen
#

and forgot to change it back

young bone
#

or remove it

celest lichen
#

removed the arg too

#

looks like this now

young bone
#

any errors?

cyan quail
#

can you paste the entire file in a codeblock here

fiery tiger
#

Yo nelo

fiery tiger
celest lichen
#

the file's pretty long and contains quite a lot of stuff that doesn't work at present, but sure

young bone
#

how many lines has the file?

celest lichen
#

91 haha

#

i have no issues when using discord.Bot and slash commands, i only get problems when i try to switch over to commands.Bot

peak wing
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name' ``` embed.add_field(name="status", value=f'{user.status}\nactivity\n{user.activity.name}')

#

this was just working earlier

celest lichen
#

here's my file

cyan quail
cyan quail
peak wing
celest lichen
#

ohhhhhhh

cyan quail
#

then change the result based on that

celest lichen
#

process_commands sort of closes the trigger of the command i guess?

#

or like, runs my await stuff?

fiery tiger
cyan quail
#

process_commands is the trigger

#

it's required in on_message for any prefix commands to work

cyan quail
peak wing
cyan quail
#

i mean...

#

if user.activity:

peak wing
#

if user.activity == None?

#

can i do that

cyan quail
#

that works too

peak wing
#

alr thanks

fiery tiger
celest lichen
fiery tiger
#
2022-08-09 02:51:15,285 - discord.http - WARNING: We are being rate limited. Retrying in 3.00 seconds. Handled under the bucket "934894551716495370:None:/channels/{channel_id}/messages/{message_id}"```
cyan quail
#

because it's assumed you're doing some other processing before checking you want to actually run the command

#

e.g. at the top you check if the author isn't the bot

celest lichen
#

gotcha

#

man, prefixed commands are a massive pain huh

#

maybe i'll just stick to slash commands lmao

#

so much boilerplate code

cyan quail
#

not really, process_commands is there by default but you just forgot to add it in your override

peak wing
# cyan quail that works too

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'activity' if user.activity == None: user.activity.name = None

cyan quail
#

..

cyan quail
fiery tiger
#

it was 5 messages

celest lichen
#

if i had no @bot.on_message event in my bot, would i not need to worry about including bot.process_commands() then?

fiery tiger
#

for some reasons a request is being made every message

#

and at 5 messages it will just ratelimit

cyan quail
celest lichen
#

gotcha

cyan quail
fiery tiger
#

spammed some As then purged

cyan quail
#

so they're definitely brand new

fiery tiger
#

yep

cyan quail
#

can you set bulk=True in purge?

fiery tiger
#

but purge shouldn't have a issue with that tho

cyan quail
#

this is default but GuraShrug

peak wing
fiery tiger
#

i was about to say that bulk cannot delete messages older than 14 days and the limit is of 100 messages

cyan quail
fiery tiger
#

but yes i can try

cyan quail
#

you should restructure your code to check for this properly

#

e.g. py name = "Some Placeholder Name" if user.activity: name = user.activity.name

fiery tiger
#

yeah but its a basic code, can't tell why this happens

cyan quail
#

that way you won't run into the issue later

peak wing
cyan quail
#

it's an example

#

currently you're doing py embed.add_field(name="status", value=f'{user.status}\n**activity**\n{user.activity.name}')

fiery tiger
#

nelo seems to work thinkCat

cyan quail
#

but if user.activity is None this will fail

cyan quail
#

which is why instead of using user.activity.name directly, you should set up a name variable beforehand and use that

fiery tiger
#

yeah nvm it doesn't

cyan quail
#

what pycord version are you on

fiery tiger
cyan quail
#

and what's the channel type

cyan quail
#

whatever you want to call the variable, it doesn't matter in the end

fiery tiger
cyan quail
#

yes

#

and what pycord version

fiery tiger
#

message channel

#

2.0

cyan quail
#

and you're being ratelimited no matter what channel you try it in

fiery tiger
#

mhm

#

i tried deleting 100

#

just meh

waxen whale
#

what are you tryin?

fiery tiger
#

me? i just worked on a simple purge command made in / commands, but it just creates a request for every single message to delete

waxen whale
#

o

fiery tiger
#

when it shouldn't... so at every 5 messages it just gets ratelimited

waxen whale
#

delete_messages should use bulk normally

fiery tiger
#

like even if the limit was 1000 it should still be a request

waxen whale
#

imma look into it if you want

fiery tiger
#

would be awesome tbh, i also looked up i just don't like it cause u cannot delete messages older than 14 days and the limit is of 100

#

but i think imma use deleted_messages looking like purge its just broke haha

#

😂

verbal gulch
#

How to use the function bot.guilds to ban a member in every server the bot is in? Like this?


@bot.slash_command()
async def mban(ctx, user, reason):
     guilds = bot.guilds
     discord.guilds.ban(user=user,      reason=reason)

I'm a bit new and sorry for bothering you.

waxen whale
waxen whale
prisma flicker
#

That's really easy, just use the random module

#

But you probably want secure random

verbal gulch
#

Or that doesn't work?

waxen whale
#

hah

#

well

#

it wont work

verbal gulch
#

Lmfao sorry i'm new and you know

waxen whale
#

because no one implemented a function for a var to ban

#
for guild in guilds
  guild.ban()

something like that i think

#

@simple canopy

#

can you help xD

verbal gulch
simple canopy
#

uh

#

async def massban(member: discord.Member, bot: discord.Bot):
  fails = []
  for guild in bot.guilds:
    try:
      await guild.ban(member)
    except HTTPException:
      fails.append(guild.name)

  return fails
#

idk something like that

#

🥴

verbal gulch
#

Oop

simple canopy
#

i just spoonfeeded

verbal gulch
#

I don't understand nothing tbh

simple canopy
#

💀

peak wing
#

mass ban?

#

thats gotta be against tos

verbal gulch
#

It is?

peak wing
#

unless its a mass ban like ban multiple members

simple canopy
peak wing
#

mass banning is just a nuke bot

#

lol

simple canopy
#

and then simply call .ban() on every of them

simple canopy
#

not sure

verbal gulch
peak wing
simple canopy
#

morally

alpine spear
#

overwhelmed.
trying to make a button with a url in it and when i pass the url kwarg in, it says "unexpected kwarg"

TypeError: button() got an unexpected keyword argument 'url'

but when i remove it, it says "url required"

400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.url: A url is required
    @discord.ui.button(label="Add to Server", style=discord.ButtonStyle.url, url = "https://discordapp.com/...")
simple canopy
#

@verbal gulch so, if you don't understand things, you should probably go learn some python

verbal gulch
simple canopy
#

you won't be able to understand things without knowledge

#

||i spoonfeeded||

verbal gulch
simple canopy
#

what exactly

verbal gulch
#

the

except HTTPException

I understand now. Thanks you

slim drum
#

whats the pycord equivalent of created_at?

simple canopy
#

oh, okay

cyan quail
simple canopy
#

i'd suggest writing this code from scratch, so you understand everything, also, i didn't implement all the checks here, so

cyan quail
waxen whale
alpine spear
cyan quail
#

no it does exist

alpine spear
#

at the bottom

cyan quail
#

but you don't need it since passing url forces it to that style

simple canopy
cyan quail
#

then add it to the view with add_item

simple canopy
#

it will be defaulted to url style if there is url kwarg iirc

cyan quail
#

yeah

alpine spear
waxen whale
alpine spear
#

oopsie

slim drum
#

is ctx.message.created_at valid?

cyan quail
#

does your view already have an init?

#

yes it is

alpine spear
#

nope

cyan quail
#

would probably be easier if it did

#

then you can create the button inside the init and do self.add_item

errant craneBOT
#
:class:`datetime.datetime`: The message's creation time in UTC.```
simple canopy
slim drum
#

tytytyty

simple canopy
celest lichen
#

how do i make an arg optional?

simple canopy
#

default it to something

celest lichen
#

so in the function def i should do like

simple canopy
#

or, if you are speaking about slash commands, there is required kwarg

celest lichen
#

yes, slash commands

simple canopy
#

you should default an arg to None (idk if it still works) or use discord.Option(required=False)

celest lichen
#

thank you!

#

does this look right?

simple canopy
#

also, i think you should specify the type of arg

#

im pretty sure its needed

celest lichen
#

discord still making me input the arg

#

how do i do that?

silver moat
#

comment out slash command and run. uncomment and run

celest lichen
#

jesus, that worked

#

why on earth did that work

silver moat
#

because pycord doesn't update commands?

cyan quail
#

pycord did update them but idk which pr in 2.0 broke it lol

#

it's perfectly fine on rc1

silver moat
#

yeah they used to update

#

when rc is more stable than stable

celest lichen
cyan quail
#

discord stores slash commands themselves

celest lichen
#

ohhhh

#

interesting

#

i should probably still set a type and a name and stuff on the arg, how do i do that?

cyan quail
#

well you can do something like arg: str=None

#

but for slash commands it's preferable to use discord.Option for better usage py arg: discord.Option(str, "Option Description", default=None)

#

there's various syntaxes for options but this is just my preference

#

...and honestly the most reliable from the reports we've seen here

celest lichen
#

man that is Lengthy

#

thank you

dreamy cargo
#

How do i reply to private messages on discord py?

silver moat
dreamy cargo
#

ok

#

like some event it can listen for?

smoky forge
#

listen for on_message and check if the message channel is a dm channel

#

or if the message guild is None

#

that is if you want to listen to incoming private messages

dreamy cargo
#

ok thank you

fervent cradle
#

Hello, how i can use followup in modal send? well response.send_modal has been disabled because i this have already..

            modal = Allgemein_Modal(title="Loads")
            await interaction.response.send_message("Loading..")
            await interaction.followup.send_modal(modal)

AttributeError: 'Webhook' object has no attribute 'send_modal'

waxen whale
#

you can't

#

you have to directly response with a modal
and you can't send another modal if a modal was received

meager heron
#

I've just received an error:

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

I only have 56 application commands. What is causing this/what can I do?

rare ice
meager heron
#

I restart this bot dozens of times a day, though

#

This was only my ... third?

fervent cradle
# waxen whale you can't

mhmm okay and how i can use edit_message ?
await interaction.response.edit_message("ss") is not works because i have already send

queen prism
#

How can I use slash commands sub groups in multiple cogs?

cyan quail
#

which timeout function

cyan quail
#

no, just make a timedelta object

queen prism
# cyan quail elaborate

I have

events_group = SlashCommandGroup("event", "event related commands!")
config_group = events_group.create_subgroup("config", "configure your server!")

I have this in a cog, I want to be able to use it in another cog, I tried using the same thing but it gives an error.

cyan quail
#

hold on

queen prism
#

Ok.

queen prism
#

I'll try that, thanks!

rotund berry
#
import random
import os
import asyncio
import datetime
from discord.ext import commands, tasks

from discord import DMChannel
import random

client = commands.Bot(command_prefix="!")




@client.event
async def on_ready():
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name='Schau bei Chailo Way was sicher ist'))
    print('Bot eingeloggt als {}'.format(client.user.name))




@client.command()
@commands.has_guild_permissions(administrator=True)
async def giveaway(ctx, mins : int, * , prize:str):

    await ctx.send("@everyone")

    embed=discord.Embed(title="GiveAway")
    embed.add_field(name="Preis", value=f"{prize}")
    end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)
    embed.add_field(name="Endet am:", value=f"{end}UTC")
    embed.set_footer(text=f"Endet in {mins} Stunde(n)!")

    my_msg = await ctx.send(embed=embed)

    await my_msg.add_reaction("✅")

    await asyncio.sleep(mins*60)

    new_msg = await ctx.channel.fetch_message(my_msg.id)

    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(client.user))

    winner = random.choice(users)

    await ctx.send(f"{winner.mention}")

    embed=discord.Embed(title="Gewinner!", description= f"{winner.mention}")
    embed.set_thumbnail(url=winner.avatar_url)
    embed.add_field(name="Preis", value=f"{prize}")
    embed.set_footer(text="GiveAway beendet!")
    await ctx.send(embed=embed)

    server = ctx.message.guild

    await winner.send(f"Du hast das giveaway von {server.name} gewonnen!")
smoky forge
rotund berry
fervent cradle
#

idk if i should be asking here but..
does anyone know the exact ratelimit for webhooks?
like how many times i can make a request to the webhook per sec or smth

smoky forge
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
smoky forge
#

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

rotund berry
smoky forge
#

?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)
smoky forge
#

you need the message_content intent for prefixed commands

rotund berry
alpine spear
#

ran into a bit of an issue with SlashCommandOptionType:

@bot.slash_command(name = "status", description = "Returns the status of a specific object")
async def specificstatus(ctx, object: discord.Option(discord.SlashCommandOptionType.string) = "user" or "player" or "creator"): #i assume this is where i put the options, but even after i remove the strings, the error still occurs
    if object == "user":
        await ctx.respond("you said user")
  async def specificstatus(ctx, object: discord.Option(discord.SlashCommandOptionType.string)):
  elif issubclass(self._raw_type, Enum) and (doc := inspect.getdoc(self._raw_type)) is not None:
TypeError: issubclass() arg 1 must be a class
smoky forge
rotund berry
smoky forge
marble jasper
#

is it possible to edit a modal while a user is on it for live input validation?

smoky forge
#

your code will not work

#

you have to set the message_content intent to true and add it to the bots intents

cyan quail
#

use str instead of discord.SlashCommandOptionType.string

alpine spear
cyan quail
alpine spear
#

first time using choices so a bit rusty

cyan quail
#

no, literally discord.Option(str, ...)

alpine spear
cyan quail
#

it's used internally, you don't need it at all

alpine spear
#

ah right

cyan quail
#

what's your code, and did you specify the message_content intent?

queen prism
alpine spear
#

what would i put for the autocomplete arg

cyan quail
queen prism
cyan quail
#

hmm hold on

queen prism
#

Ok.

cyan quail
cyan quail
alpine spear
queen prism
cyan quail
#

that should capture all types of commands

queen prism
#

hold on I'll try that.

cyan quail
#

oh i see

queen prism
cyan quail
# queen prism Still None.

my mistake, for some god forsaken reason this isn't documented... command groups have an attribute called subcommands
i recommend using discord.utils.get(group.subcommands, name="...")

#

where group is the group you got from get_application_command, type=SlashCommandGroup

queen prism
#

I'll try that.

queen prism
#

I tried

grp = get(self.client.get_application_command("event", type = discord.SlashCommandGroup).subcommands, name = "config")

@grp.command()
...

but that didn't work.

cyan quail
#

just checking, config is a group?

queen prism
#

config is the subgroup.

#

event is the group.

cyan quail
#

that should work fine, but note this likely won't work if the bot has already started

#

it'll only work before the on_ready event has fired

queen prism
#

How can I do that? Any suggestions?

cyan quail
#

wait so what are you trying to do

queen prism
#

I created a subgroup in a cog, and now I'm trying to use the same subgroup from another cog.

celest lichen
#

how do i get the channel id of a message from a on_message event?

#

message.channel just gives me the name of the channel in plaintext

queen prism
celest lichen
#

hahaha yeah that's simpler than i was expecting

cyan quail
# queen prism I created a subgroup in a cog, and now I'm trying to use the same subgroup from ...

kind of weird since you can't use the decorator in the init i think...?
what you could try in the init is something like ```py
class SomeCog(Cog):

def init(self, bot):
self.bot = bot
self.group = get(groups... etc whatever your subgroup is)
new_cmd = discord.SlashCommand(name="idk", parent=self.group, callback=self.command_logic)

async def command_logic(self, ctx):
# your command code```

#

basically, instead of using the decorator you attempt to construct the command yourself and assign the parent

#

this is just something i theorised so i can't guarantee it'll work, but possibly worth a shot

queen prism
#

Alright. I'll try that.

cyan quail
#

otherwise i think you'd be better off just doing it in the same cog

queen prism
#
class Test(commands.Cog):
    def __init__(self, client):
        self.client = client

    
    config_group = get(self.client.get_application_command('event', type = discord.SlashCommandGroup).subcommands, name = 'config')


    @config_group.command()
    async def test(self, ctx):

that's what I had before.

cyan quail
#

that won't work because you can't access self there so it'd break

queen prism
#

I see.

cyan quail
#

also in load_extension make sure you have store=False so errors will show

queen prism
#

Will do.

#

The slash command group return None because the second cog loads before the group is created.

#

I think I'll just use one cog file at this point, thanks.

prisma flicker
cyan quail
#

store=False was always the behavior before 2.0

#

or rather it didn't even exist

#

you can just do ctx.edit if it's in a command

prisma flicker
#

so what's the difference other than showing errors?

cyan quail
#

instead of raising errors, store=True returns the error(s) in a dict

#

which is useful if you use load_extension to load a folder instead of looping through cog names

prisma flicker
#

it's a dict of cog to error?

#

interesting

cyan quail
#

yep

#

but no one knew about the change lol

#

outside of the pr

orchid hull
#

Hi, I'm using a type-checker for development. When I try to create a bot variable, such as client.command_list = {}, I get the following type error:

Cannot assign member "command_list" for type "Bot"
  Member "command_list" is unknown```
Is there any way I can mitigate the type error without suppressing it?
Thanks.
cyan quail
#

can you show the code anyway

orchid hull
#

btw @cyan quail, thanks for the help yesterday. I forgot to thank you.

cyan quail
#

all good

#

so does followup.edit not work?

cyan quail
#

though bots already have internal command lists

orchid hull
cyan quail
#

?

#

not really

orchid hull
cyan quail
#

cog creation is also a form of subclassing

orchid hull
#

Do you have a link to a good guide on client subclassing?

#

I'll try out since I have a whole file for managing the bot instance

orchid hull
cyan quail
#

ah so your command_list is manually formed?

orchid hull
#

Here's the real code, I cut it off for simplicity: py client.command_list = requests.get( "https://website.com/commands.json", headers={"User-Agent": api.user_agent} ).json()

#

I have a page on my website at /commands that displays commands from that JSON

cyan quail
#

oh it should be followup.edit_message

#

ah fair enough then

orchid hull
fervent cradle
cyan quail
orchid hull
cyan quail
#

whatever you normally use

orchid hull
#

I'm using commands.Bot, so I'll use that then.

fervent cradle
cyan quail
#

allgood

orchid hull
#

So essentially, the gist is to do ```py
class _Client(commands.Bot):
def init(self) -> None:
self.foo = 'bar'

@self.event
async def on_connect(self) -> None:
...

client = _Client()

#

?

cyan quail
#

nah you dont need the decorator

#

it'll override them without

orchid hull
cyan quail
#

that's just python

orchid hull
cyan quail
#

yeah

orchid hull
#

Cool.

cyan quail
#

give it a try on a test setup if necessary

orchid hull
#

👍 Got it, thanks!

#

Gotta rewrite this fat manager file now lol

#

@cyan quail - sorry for the ping. How would I write my init to keep my original commands.Bot kwargs?

#

Do I have to do super().__init__(...)

fiery tiger
#

and for example i can do just

deleted_messages = await channel.delete_messages(limit, bulk=True)

#

correct?

#

wait

#

without bulk my bad, forgot to remove

#

wait it cannot be an int

proud pagoda
orchid hull
#

How can I use @bot.check when subclassing a bot?

fiery tiger
#
    messages = await channel.history(limit=limit)
TypeError: object HistoryIterator can't be used in 'await' expression
#

nvm flatten

#

works

cyan quail
#

as for bot.check, you could just do it like normal outside the class

#

i think there would be a way to do it inside but not entirely sure, maybe discord.Cog.bot_check?

orchid hull
cyan quail
#

no, that's cog_check

#

Cog.bot_check should work for a global check

fiery tiger
#

Nelo

#

i got a question about bulk

#

like in the docs it says that it cannot bulk messages older than 14 days

#

what if someone inputs a limit of 100 messages and 20 of them are new and let's say the others has been sent years ago

#

what is it going to? i suppose it will just be a error in the terminal.

#

how can i make the bot delete the 20 new messages and automatically stop when it cannot fetch the messages history no more

cyan quail
cyan quail
fiery tiger
#

oh awesome

orchid hull
cyan quail
orchid hull
cyan quail
#

not necessarily

orchid hull
#

I'm using it inside a cog

fast totem
#

yo

cyan quail
#

oh it should still work

#

commands.bot_check doesn't exist

fast totem
#

does anyone know the docs link for custom bot status?

cyan quail
#

it's like how we use commands.Cog.listener

#

i guess maybe commands.Cog.bot_check then but either should work

orchid hull
#

discord.Cog doesn't exist, so I don't think it could be that

cyan quail
#

it does

orchid hull
#

"Cog" is not a known member of module

cyan quail
#

cogs are no longer exclusive to the commands extension

orchid hull
#

Ah ok

cyan quail
#

maybe you're on an older version? it definitely exists

orchid hull
#

Yeah I am

#

@commands.Cog.bot_check throws an error though

cyan quail
#

what is it

orchid hull
#

Argument missing for parameter "ctx"

#

This is my usage

cyan quail
#

oops wrong reply

orchid hull
#

Argument missing for parameter "ctx"

#

@commands.Cog.bot_check(self)

cyan quail
cyan quail
#

then no (self) on decorator

#

or maybe

#

could you try just ctx, without typehinting

orchid hull
#

Arguments missing for parameters "self", "ctx"

#

Is what I get now

cyan quail
#

huh

#

so the first one worked best... odd

orchid hull
#

Is this even a decorator? The docs refer to it as a method

slim drum
#

i keep getting AttributeError: 'property' object has no attribute 'url' whenever i try to use a server's icon (url) as a thumbnail for an embed. i read the docs and saw a post here and both said to use discord.Guild.icon.url but that doesnt work

embed.set_thumbnail(url=f"{discord.Guild.icon.url}")
fast totem
#

but can't set status that change itself after a certain ammount of time

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.

cyan quail
#

just define bot_check anywhere inside the cog and it should work

silver moat
#

likewise, Guild is a class

fast totem
#

i tryed myself basic python but something got wrong

fast totem
#

bruh idk anymore

#

i mixed with a while loop and random.choice

#

but gone so wrong

cyan quail
#

please don't use a while loop for this

#

so i take you want to change the status every few minutes?

fast totem
#

yeah

#

something like that

cyan quail
fast totem
#

ok

#

ty

fiery tiger
#

@cyan quail this used to work what changed?

cyan quail
#

guild no longer has a region

#

it's now on individual voice channels

fiery tiger
#

oh alright

fiery tiger
#

i also have a question

#

this happened after i updated the packages

#

why are the buttons

#

fucked like... they work even tho they say interaction failed

#

LOL

#

also i see this doesn't work anymore

cyan quail
#

what discord.__version__ and code

#

ohh

#

there was an api change to how guild.bans works

fiery tiger
cyan quail
fiery tiger
#

about the buttons i still dont know

#

oh u mean pycord version

#

v2

fiery tiger
cyan quail
#

maybe just use a big limit

fiery tiger
#

limit none

#

shouldn't it just be limit none?

cyan quail
#

maybe that works

#

actually no, if you do None it defaults to 1000

fiery tiger
#

i will just go with default

fiery tiger
cyan quail
#

...found a bug

#

how did no one notice this

#

oh wel

fiery tiger
#

what-

#

😂

cyan quail
#

1000 or above returns all bans

#

999 or below works fine

fiery tiger
#

so none will get all of them right?

cyan quail
#

yes

fiery tiger
#

awesome

#

can u check the button thingy?

#

they work but still says some fail issue when clicking

cyan quail
#

which ones work and which ones dont work

#

or is this all of them

fiery tiger
#

all of them haha

#

its like when u make an interaction

#

the interaction of the number / sign will be added to the embed message

#

it will load for a few secs then interaction failed

#

even tho it works 😂

#

still calculating.. everything working fine

#

i just get that error lol

cyan quail
#

button.callback = callback.__get__(button, Button) ... why?

#

oh i see your issue

#

you're not responding lol

#

use interaction.response.edit_message instead of interaction.message.edit

fiery tiger
#

ohhh

fiery tiger
cyan quail
#

nah that's fine, ignore me

fiery tiger
#

i mean last change yesterday.. black format

#

thanks nelo

#

it works very well now haha

fiery tiger
#

i see it works a bit more different... how could i get how many users are banned

#

like enumerate them

cyan quail
#

there's an example on the docs page

#

using flatten

fiery tiger
#

flatten will get the list

#

i seen

cyan quail
#

so then just get the length of it

fiery tiger
#

awesome

fiery tiger
peak wing
#
In embeds.0.fields.4.value: Must be 1024 or fewer in length.``` ```  @commands.command(aliases = ["si"])
  async def serverinfo(self, ctx):
    time = ctx.guild.created_at.timestamp()
    embed = discord.Embed(title=f"", description="", color = 0x303135)
    embed.add_field(name='owner', value=f"{ctx.guild.owner}", inline=False)
    embed.add_field(name='created', value=f"<t:{int(time)}:R>", inline=False)
    embed.add_field(name='members', value=f"{ctx.guild.member_count}", inline=False)
    embed.add_field(name='channels', value=f"{len(ctx.guild.text_channels)}", inline=True)
    embed.add_field(name='roles', value=f"{ctx.guild.roles}", inline=True)
    embed.add_field(name='images', value=f"[icon](ctx.guild.icon.url)\n[splash](ctx.guild.splash.url)\n[banner](ctx.guild.banner.url)", inline=True)
    embed.add_field(name='boost', value=f"t", inline=True)
    embed.set_thumbnail(url=ctx.guild.icon.url)
    embed.set_footer(text=f"ID: {ctx.guild.id}") 
    embed.set_author(icon_url=self.bot.user.avatar.url, name='cope')
    await ctx.send(embed=embed)``` why am i getting this error?
fiery tiger
#

you are doing something wrong.. probably pulling an entire list and it just wont fit in the embed field

peak wing
#

your seeing all the code

fiery tiger
#

yes

#

i think its coming from ctx.guild.roles

cyan quail
peak wing
#

yep, it was

#

how do i get the guild role count then?

cyan quail
#

check the length of it

peak wing
cyan quail
#

it's a list....

woeful spindle
#

Hey, so I have this code and I’m trying to get a cog, using bot.get_cog method. But, everytime I use it, it says bot isn’t defined. I’ve tried self.bot, yet that doesn’t work either? What do I do?
Code: https://mystb.in/DellLiteRick

fiery tiger
#

Nelo

#
    async def unban(self, ctx: discord.ApplicationContext, user: int):

        banned_users = await ctx.guild.bans(limit=None).flatten()

        for ban_entry in banned_users:
            user = ban_entry.user
            if user.id == user:
                await ctx.guild.unban(user)
                await ctx.respond(f"{settings.emojis.proceed} **{user}** Has been unbanned from the guild!")
cyan quail
#

inside a callback, you can access bot with interaction.client

fiery tiger
fiery tiger
#

lemme see where the code stops cuz idk lol

cyan quail
#

you might need to defer if you're using guild.bans

#

also you really don't need to do that

fiery tiger
#

it will just stop before the if statement

cyan quail
#

then banentry.user was none

#

but again, this is very inefficient

#

it will raise an error if the user isn't banned

fiery tiger
#

alright let's see

#

no errors

#

await ctx.guild.fetch_ban(user)

cyan quail
#

user being the user object yes?

#

not just an ID

fiery tiger
#

i mean im using the ID

#

that's why i have the user as a int parameter

#

and then im checking the user id

cyan quail
#

also i might be wrong, but i don't think int will accept user IDs?

fiery tiger
#

it worked before api changes honestly

cyan quail
#

using discord.User will automatically convert the ID to user though

fiery tiger
#

does it? so its better than int?

peak wing
cyan quail
#

same with other types like Member, Role, TextChannel; they all accept IDs

fiery tiger
#

oh

fiery tiger
fiery tiger
#

wait wait wait

#

nelo

#

is there a way to display the banned users? in a / command

#

like automatically then typing having a autocomplete for user name or id

cyan quail
#

well yeah you can just iterate through guild.bans

fiery tiger
#

cause that would be just better tbh

cyan quail
#

you could do it in autocomplete but be very careful

fiery tiger
#

what do u mean sadcatthumbsup

cyan quail
#

if you just stick guild.bans in autocomplete you'll be ratelimited to hell and back

peak wing
#
``` why isn't these hyperlinks when i send the embed?
cyan quail
#

can you show a screenshot

peak wing
woeful spindle
#

How do I access my bots avatar via using interaction.client?

woeful spindle
#

ty

cyan quail
#

or display_avatar if it isnt set

woeful spindle
#

display_avatar caused errors for me

woeful spindle
cyan quail
cyan quail
woeful spindle
cyan quail
#

you're missing user

woeful spindle
#

replied to the wrong message

cyan quail
#

you need client.user

woeful spindle
peak wing
#

how do you get a guild boost level?

cyan quail
woeful spindle
#

Right, so I have this code, it does everything I want, but it removes one letter from the end of my command name? How do I change this?

elif select.values[0] == "info":
            info_cog = interaction.client.get_cog(name='Info')
            info_commands = info_cog.get_commands()
            joined = "`, `".join(command.name for command in info_commands[:-1])
            e = discord.Embed(
                color=0x2f3136,
                description=f"Please use **!help <command>** for more infomation on any specific command.\n\n**Commands:**\n`{joined[:-1]}`"
            )
            e.set_author(name="Here are our Infomational commands:",icon_url=interaction.client.user.display_avatar.url)
            e.set_footer(text=f"Infomation requested by {interaction.user}",icon_url=interaction.user.display_avatar.url)
            e.set_thumbnail(url=interaction.client.user.display_avatar.url)
            await interaction.response.edit_message(embed=e)
empty tree
#

you might want just {joined}

woeful spindle
empty tree
#

np

storm geode
fallen cove
#

how would you use

mentions = interaction.message.mentions
for mention in mentions:
    await mention.add_role(role)```
but to get the same effect if the mention is in an embed
fast totem
#

yo

#

guys i have a question about vps

#

is a vps host rate limit proof?

#

like

#

rate limit proof is a strong word

#

i would say: have less rate limits than replit?

silver moat
fast totem
#

anything is better than replit lol

#

but it's like vs code?

#

can i code without fear

silver moat
#

vs code is a code editor

fast totem
#

oh yes

#

anyways ty i'll search for some tutorials

peak wing
#
  async def color(self, ctx):
    if ctx.invoked_subcommand is None:
        await ctx.send('color embed')


  @color.command(name = 'set')
  async def mycolor(self, ctx, color):
    name = {ctx.author.name}
    if name in ctx.author.roles:
        embed2 = discord.Embed(description = f'you already have a color', color=0x303135)
        return await ctx.send(embed=embed2)


    ape = await ctx.guild.create_role(name=f'{ctx.author.name}', color=int(f'0x{color}', 16))
    await ctx.author.add_roles(ape)
    embed = discord.Embed(description = f'{ctx.author.mention} assigned your color to {color}', color=int(f'0x{color}', 16))
    await ctx.send(embed=embed)```
#

why is it still creating and giving me the role twice even though i set a if statement to prevent that?

round rivet
#

author.roles is a list of role objects

#

so a set with the author's name is never going to be in it

peak wing
full basin
#

author.roles is a list of role objects

peak wing
#

ohh

#

how do i fix this?

#

@full basin

prisma flicker
#

if "har" in [role.name for role in author.roles]

#

@peak wing

peak wing
fiery tiger
#

How can i make an autocomplete for banned members?

#

my brain is not telling me the logic to do that lol

#
async def get_autocomplete(ctx: discord.AutocompleteContext):
    async for ban in ctx.guild.bans(limit=None):
        user_id = ban.user.id
#
            discord.Option(
                discord.enums.SlashCommandOptionType.string,
                name="query",
                description="Who are you trying to unban?",
                required=True,
                autocomplete=discord.utils.basic_autocomplete(get_autocomplete)
            )
#

i need help with some logic 😂

prisma flicker
#

just put them in a list and return it

fiery tiger
#

thanks

#

oh yes the user name or id?

prisma flicker
#

up to you

#

what do you want your users to see

fiery tiger
#

they're name

#

i didn't know if it would work without ID but that would be great

#

does it display the user profile picture too?

#

or just its name ?

fast totem
#

can i create a vps host for more than a single bot?

fast totem
#

nice

#

i mean

#

awesome

kindred sail
#

as long as its powerful enough (which almost anyone should be) you can run multiple

fast totem
#

hm

#

okay

#

ty

kindred sail
#

np

prisma flicker
prisma flicker
#

4 cpus and 8 gb of ram

#

probably overkill tbh

fast totem
#

bruh

#

then its fine

#

i will use like 2 bots

prisma flicker
#

they're all in one server each and most of them are barely used 😄

#

only two are really used a lot

fiery tiger
#
banned_users = []
async def get_autocomplete(ctx: discord.AutocompleteContext):
    async for ban in ctx.guild.bans(limit=None):
        banned_users.append(ban)
prisma flicker
#

put the list in the method

fiery tiger
#

will this way work?

prisma flicker
#
async def get_autocomplete(ctx: discord.AutocompleteContext):
    banned_users = []
    async for ban in ctx.guild.bans(limit=None):
        banned_users.append(ban)```
#

no need to have it outside

fiery tiger
#

👍

#

yeah but

#

i think its going to be an atr error

prisma flicker
#

why?

fiery tiger
#

looking at it ctx is using discord autocomplete context

#

i don't know just saying lol

#

i will try and let u know...

prisma flicker
#

try it

fiery tiger
#

alright

#

yup, i knew i had this issue some time ago

#

@prisma flicker

round rivet
#

try using get_guild with ctx.guild_id

fiery tiger
#

sorry what?

round rivet
#

also because guild.bans is an asynciterator you can use .flatten with it

round rivet
prisma flicker
fiery tiger
#

i didn't know i could use get_guild

fiery tiger
prisma flicker
#

did you forget to await?

fiery tiger
#

yes...

#

But await won't do much

#

considering it's still a nonetype

prisma flicker
#

what's None?

fiery tiger
prisma flicker
#

yes but what is None

#

guild? bans?

fiery tiger
#

from that error i don't understand much but i suppose bans

#

i tried await just now

prisma flicker
#

so do some debugging to find out what's None

fiery tiger
#

still a nonetype

prisma flicker
#

and please just send your code and errors as text

fiery tiger
#

alr

#

its just huge haha

prisma flicker
#

yeah don't await the append...

#

that's just adding to a list, it's not async

fiery tiger
#

sorry im just being so fucked rn

prisma flicker
#

exactly, it's hard to see what's wrong without the full error

fiery tiger
#

the issues i had a long time ago

#

are so fucked rn

#

im having so many errors at a time

#

can't manage this shit no more

#

also the calculator jesus

prisma flicker
#

cut out most of the code, and start adding it piece by piece and when you get an error tackle it then

fiery tiger
#

yes this happened after i updated all the pips

#

packages..

prisma flicker
#

maybe make a new thread too

fiery tiger
#

look i wanna leave that unban command for a sec

#

i wanna take them in order

#

else im just gonna lose my brain around

#

fucking 3 am cant even think properly lol

prisma flicker
#

general help is really for quick single issues

#

you have lots of issues so you should have your own post 😄

fiery tiger
#

😂

#

i mean i have quick single issues

#

but many of them lol

#

😂

prisma flicker
#

just make a new post and put your code and full stack trace there

fiery tiger
#

post where?

#

lol

prisma flicker
#

#969574202413838426

fiery tiger
#

oh

#

will do

#

but now i do have a quick issue this time

#

1 sec lemme do a test rq

#

this was clearly not happening before lol

#

lemme look for a older message

fiery tiger
#

This is why lol i didn't notice at first, i have to edit the message tho, else it will say interaction failed even tho it works lol

prisma flicker
#

so what's the issue?

fiery tiger
#

give me a second i don't even know rn

#

fixed it myself my bad

#

Yeah i will just go ahead and create a post for the unban

fiery tiger
prisma flicker
#

idk

fiery tiger
#

i also got #1006723806641016843 if u wanna help lol

fervent cradle
#

Is it possible to change the slash command defaults in the bot integration?

prisma flicker
#

wdym defaults?

fervent cradle
prisma flicker
#

ah right, I'm pretty sure it is using decorators

celest lichen
#

currently trying to set up some database stuff with my bot for storing toggles and stuff. i'm using heroku for bot hosting, so i went with the heroku postgresql addon for my database

#

it's just occurred to me it might be because i don't have the postgresql server installed? but i'm using the remote db on heroku so i won't end up using it

#

nope

copper dew
#

or check if postgres.app bundled pg_config with it as well

hushed ledge
#

One message removed from a suspended account.

rare ice
hushed ledge
hushed ledge
rare ice
#

b!rtfm followup.send_modal

dire spadeBOT
# rare ice b!rtfm followup.send_modal

I couldn't find a documentation with the name followup.send_modal! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

hushed ledge
#

One message removed from a suspended account.

rare ice
#

b!rtfm pyc followup.send_modal

dire spadeBOT
rare ice
#

yeah you can’t follow up a modal interaction

hushed ledge
#

One message removed from a suspended account.

rare ice
dire spadeBOT
rare ice
#

huh

#

huh

#

Idk why it’s not in the docs but it’s await interaction.followup.edit_message(message_id=interaction.message.id) - you have to provide the interaction message ID

#

@hushed ledge

hushed ledge
tall quail
#

is there anyway to get this information in a button class callback if the slash command response has this button?

#

i tried interaction.message.interaction.data but that just includes the name of the command, not the options

prisma flicker
#

does interaction_check get called before any of the button callbacks?

prisma flicker
#

are snowflakes guaranteed to be sorted by creation date?

tall quail
prisma flicker
#

it is though

#

at least it is in on_interaction

tall quail
#

¯_(ツ)_/¯

#

im surprised this isnt possible as the discord client shows what options they used

prisma flicker
#

Is that everything in data?

tall quail
#

yes

spiral sail
#

Need to check — is it possible to have an embed with always-on buttons? So let’s say e.g. ticket tool always has a ticket panel listening to when someone presses the button to create a ticket.
Is there a way to recreate this in Pycord so even if the bot is restarted, the view would still work?

#

(Im not recreating a ticket tool, just an example)

prisma flicker
#

Yes you just need a persistent view

spiral sail
frank yew
#

Who compare reactions with str?
like this? if reaction == ":one_stars:":

simple canopy
#

read your error

sterile canopy
#

why is only the latter button sent in this code?

    def __init__(self):
        super().__init__(timeout=None)
    
    @discord.ui.button(label="Enter Code", style=discord.ButtonStyle.gray,custom_id='enter_code')
    async def button_callback(self, button, interaction):
        await interaction.response.send_modal(EnterVerificationCode(title="Verification"))
        
    @discord.ui.button(label="Send code", style=discord.ButtonStyle.green,custom_id='send_code')
    async def button_callback(self, button, interaction):
        code = generateVerificationCode(interaction.user.id)
        await interaction.user.send(f'Your verification code is {code}')
sterile canopy
cyan quail
#

you can see this in practice in some methods; e.g. the before and after parameters in functions like purge and history just compare the snowflakes without any conversion

frank yew
#

How can I get all messages from a channel?

frank yew
#

I do this:

async for message in channel.history(limit=None):

But I have this error:
AttributeError: 'TextChannel' object has no attribute 'news'

cyan quail
#

update your pycord

frank yew
#

How?

young bone
#

uninstall py-cord and install py-cord==2.0.0

frank yew
#

Yes I have this version

#

@cyan quail @young bone Now I have this error: ```discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

cyan quail
#

what code

frank yew
# cyan quail what code

async for message in channel.history(limit=None):

But If I change limit=None to limit=200 its working

cyan quail
#

it's because limit=None takes a long time

#

especially if the channel has more messages

#

you need to await ctx.defer() before that

frank yew
#

Thnks bro

harsh dust
#

How do I import a cog that is within another folder in the cogs directory?

#

so like, i have the cogs folder, but then i have cogs/gamemodes folder,
how would i import cogs from inside cogs/gamemodes

#

cogs.gamemodes.file does not work

fervent cradle
#

How do i defer after already responding to a command? I have a confirmation message that appears where the user has to respond with y or n. If they respond with y the command will continue. How do i defer after that point?

young bone
harsh dust
#

i'm already using that

for filename in filter(lambda k: k.endswith('.py'), os.listdir('./cogs')):
    bot.load_extension(f'cogs.{filename[:-3]}', store=False)
    print(f"Successfully loaded {filename[:-3]}")

for filename in os.listdir('./cogs/gamemodes')[1:]:
    bot.load_extension(f'cogs.gamemodes.{filename[:-3]}', store=False)
    print(f"Successfully loaded {filename[:-3]}")
#

the 2nd for loop is the one that doesnt work

rocky stump
#

Is it a security flaw if my bot is downloading images sent onto discord servers? Should I only download those with a https://cdn.discordapp.com/attachments/.... url ? Or does this not make a difference

round rivet
#

if you make sure they're images or just dont evaluate them as anything but images you should be fine

frank yew
#

Anyone have a bot with SlashCommandGroup?

harsh dust
round rivet
frank yew
#

I dont know that is it xd

frank yew
harsh dust
#

there are examples with SlashCommandGroup here

frank yew
#

Ouh I had not seen it before

#

Ty

fervent cradle
#

Hello

#

I have my bot able to nickname the users

#

How do u grab the authors name, but then use it with string without the numbers

harsh dust
#

ctx.author.name

#

ctx.author.display_name

harsh dust
#

this is my cog class:

class Progress:
    progress = SlashCommandGroup("progress", "View Quest Progress")

class Completions:
    completions = SlashCommandGroup("completions", "View Individual Quest Completions")
class Arcade(commands.Cog, Progress, Completions):
    progress = Progress.progress
    completions = Completions.completions

    def __init__(self, bot):
        super().__init__()
        self.bot = bot

    @progress.command(name="arcade", guild_ids=[763520052484898886])
    async def arcade_progress(self, ctx: discord.ApplicationContext,
                              username: Option(str, ".", default="", required=False, autocomplete=get_player)):
        """View Arcade questing progress"""
        await ctx.respond("progress: arcade")

    @completions.command(name="arcade", guild_ids=[763520052484898886])
    async def arcade_completions(self, ctx: discord.ApplicationContext,
                                 username: Option(str, ".", default="", required=False, autocomplete=get_player)):
        """View Arcade individual quest completions"""
        await ctx.respond("completions: arcade")

    @arcade_progress.error
    @arcade_completions.error
    async def on_application_command_error(self, ctx: discord.ApplicationContext, error):
        await handleError(ctx, error, bot=self.bot)

When loading the cog, I get this error:

Ignoring exception in on_connect
Traceback (most recent call last):
  File "discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "discord\bot.py", line 1041, in on_connect
    await self.sync_commands()
  File "discord\bot.py", line 628, in sync_commands
    registered_commands = await self.register_commands(
  File "discord\bot.py", line 528, in register_commands
    registered = await register("bulk", data, _log=False)
  File "discord\http.py", line 360, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 0.options: Must be 25 or fewer in length.
In 1.options: Must be 25 or fewer in length.
In 2.options: Must be 25 or fewer in length.
In 3.options: Must be 25 or fewer in length.

any idea on how to fix this?

smoky forge
#

your autocomplete might exceed the max length of items

harsh dust
#

It only has 15 items

#

solved it

frank yew
#

Can I pass something info in view?

#

I do this:


class PlsRoleView(discord.ui.View):
    def __init__(self, rol, reason):
        self.rol = rol
        self.reason = reason

    @discord.ui.button(label="Button 1", row=0, style=discord.ButtonStyle.success)
    async def first_button_callback(self, button, interaction):
        await interaction.user.add_roles(self.rol, atomic=True)
        await interaction.response.send_message("Aceptar")

    @discord.ui.button(label="Button 2", row=0, style=discord.ButtonStyle.danger)
    async def second_button_callback(self, button, interaction):
        await interaction.user.dm_channel.send(f'Se ha rechazado tu solicitud')
        await interaction.response.send_message("Rechazar")

But this dont work

cold rover
#

my select interaction is failed.
i edit original message in select, and it's my response, but discord send me interaction failed

cerulean drum
frank yew
harsh dust
#

i have a slash command group, how do i pass this down to multiple cogs

#

creating the same slash command group with the same name won't work

simple canopy
#

i'd like to know too

fervent cradle
#
confirm = await ctx.respond('Yes or No?')

response = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id, timeout=60.0)

if response.content.lower() not in ('yes', 'y', 'yup', 'sure', 'ok'):
  await ctx.respond('No')

else:
  await ctx.defer()
  #Long request here
  await confirm.edit_original_message('Done')

How do i properly defer after the user has responded with 'yes'? The request takes longer than 3 minutes so the response doesnt send.

prisma flicker
cyan quail
cyan quail
fervent cradle
#

but after they confirm the request can take longer than 5 minutes

cyan quail
#

Deferring is only necessary if the initial response will take longer than 3 seconds

fervent cradle
#

Right so it doesnt matter how long the response takes?

cyan quail
#

Probably not

#

Just give it a try I guess

#

(Also if you're doing confirmations, buttons are far nicer)

dry echo
#

does someone have a tutorial for playing audio in pycord?

harsh dust
#

but now im getting more errors

simple canopy
harsh dust
#

if more than 1 cog is using the group all of a sudden it throws this error which also makes all the other slash commands not work

Ignoring exception in on_connect
Traceback (most recent call last):
  File "B:\Development\Python\Projects\Discord Bots\Questify\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "B:\Development\Python\Projects\Discord Bots\Questify\discord\bot.py", line 1041, in on_connect
    await self.sync_commands()
  File "B:\Development\Python\Projects\Discord Bots\Questify\discord\bot.py", line 628, in sync_commands
    registered_commands = await self.register_commands(
  File "B:\Development\Python\Projects\Discord Bots\Questify\discord\bot.py", line 528, in register_commands
    registered = await register("bulk", data, _log=False)
  File "B:\Development\Python\Projects\Discord Bots\Questify\discord\http.py", line 360, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 3: Application command names must be unique

however with 1 cog its fine

lost lodge
#

Hello, anyone know how to make a button work after restart?

errant craneBOT
#

Here's the persistent example.

proud pagoda
#

Is there any way to check whether the bot can DM a user without actually sending them a message first? Ping on reply please

fervent cradle
short quartz
#

My friend was wondering what this meant, I’m trying to help him

rocky stump