#Basic Pycord Help (Quick Questions Only)
1 messages · Page 8 of 1
I mean randint works best for rgb values
How can I get all messages in a channel?
i also tried to use a specific color but that didnt seem to work either
Here's the docs for the class needed: https://docs.pycord.dev/en/master/api.html?highlight=color#colour
But what u can do is to swap out the randint for something like this:
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)))
tysm!! ill try it and update you
ah np !
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)
are you trying to do random embed colors?
yup
you can instead use discord.Color.random()
and for this code, C have to be capital
ah tyty
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
/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
How can i ignor bot message in on_message event
If message.author.bot:
return
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:
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
ok
i really cant see any problems with it but the cog still doesnt show up
hmm i dont see anything wrong
try printing out the list you are getting in your cog loader
after this part, add this:
print(bot.extensions)``` and send output
may be there is something you'll need to replace and/or change
btw i use class General(commands.Cog): and not (discord.Cog) if that changes anything
it wont change anything i believe
hm
it won't work because bot.run() will block any code from below for the time of bot actually working
im using replit if that changes anything
ive installed the pycord package and removed the discord.py/discord one
then meaning that the cog isnt loading.... you could try manually loading the cog and see if there is errors or smth
!replit
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
How to install the Py-cord library - Pycord Guide
if its the code you are using rn,
how do i manually load it?
makesure u install it correctly..
^ try this
but it isn't loading... breh
this is the only command that shows up
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
same result

welp
maybe its a replit problem, ill run my code using visual studio code and see if it works
reverting changes might fix your problem...
@outer obsidian @simple canopy the response i get from VSC
name shouldn't be a list
it must be a string
for example:
name='avatar'
AH OMG
ohhh!!!
you can only have list on aliases
i didn't see it tooo
FUCK IM STUPID, I SAW IT AND DIDN'T EVEN NOTICE
i tot it was aliases
slashes can't have aliases
aaahh okay
yeah but prefixed command can so idk if will it work on bridge cmd...
im used to discord.py pre v2.0 my bad
don't think so
not sure, i use only slash
i dont use bridge, i use only slash or only prefixed lmao
this should work right?
yep
np
How can i ignor bot message in on_message event
Спасибо
ik it's fixed now, but add store=False as a kwarg in load_extension
нема за що :)
uhm...im kinda new to coding in general since im learning how to code using discord python but this is correct right?
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
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
Any error?
You're defining your command as (ctx, arg), so if you're running the command without providing any argument it should raise an error.
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
ctx.respond at a prefix command
you need ctx.send or ctx.reply
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
add to the arg =None
and forgot to change it back
or remove it
any errors?
can you paste the entire file in a codeblock here
Yo nelo
https://hastebin.com/eleyoduwom.py - why this creates a request every message... again
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the file's pretty long and contains quite a lot of stuff that doesn't work at present, but sure
how many lines has the file?
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
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
here's my file
user doesn't have an activity set
any specific in the console?
you need await bot.process_commands() at the end of your on_message
how do i set the activity to None and still send the embed
ohhhhhhh
just check if user.activity isn't None
then change the result based on that
process_commands sort of closes the trigger of the command i guess?
or like, runs my await stuff?
nah just the ratelimit coming up every 5 messages...
process_commands is the trigger
it's required in on_message for any prefix commands to work
can you actually show what it looks like
how would i go about doing that?
that works too
alr thanks
yep
why is it important it's at the end of my on_message?
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}"```
it doesn't have to be, but that's typically where you put it
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
gotcha
man, prefixed commands are a massive pain huh
maybe i'll just stick to slash commands lmao
so much boilerplate code
not really, process_commands is there by default but you just forgot to add it in your override
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'activity' if user.activity == None: user.activity.name = None
..
nelo
how much are you trying to purge
it was 5 messages
if i had no @bot.on_message event in my bot, would i not need to worry about including bot.process_commands() then?
for some reasons a request is being made every message
and at 5 messages it will just ratelimit
pretty much, but it's literally a single line of code
gotcha
how old are the messages
it was a few seconds
spammed some As then purged
so they're definitely brand new
yep
can you set bulk=True in purge?
but purge shouldn't have a issue with that tho
this is default but 
nelo do you know how i can fix this?
i was about to say that bulk cannot delete messages older than 14 days and the limit is of 100 messages
if user.activity is None, then activity.name doesn't exist because activity is None
but yes i can try
you should restructure your code to check for this properly
e.g. py name = "Some Placeholder Name" if user.activity: name = user.activity.name
yeah but its a basic code, can't tell why this happens
that way you won't run into the issue later
isn't this my code but tweaked im confused
it's an example
currently you're doing py embed.add_field(name="status", value=f'{user.status}\n**activity**\n{user.activity.name}')
nelo seems to work 
but if user.activity is None this will fail
yeah
which is why instead of using user.activity.name directly, you should set up a name variable beforehand and use that
yeah nvm it doesn't
what pycord version are you on
and what's the channel type
but name is there status
whatever you want to call the variable, it doesn't matter in the end
r u talkin to me?
and you're being ratelimited no matter what channel you try it in
what are you tryin?
me? i just worked on a simple purge command made in / commands, but it just creates a request for every single message to delete
o
when it shouldn't... so at every 5 messages it just gets ratelimited
delete_messages should use bulk normally
like even if the limit was 1000 it should still be a request
imma look into it if you want
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
😂
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.
well we can't do anything against the limit
nah, guilds.ban doesn't exist. you would've to do it in an for function and with try except because you won't know if you have perms everywhere
That's really easy, just use the random module
But you probably want secure random
'guilds' is a variable
Or that doesn't work?
Lmfao sorry i'm new and you know
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

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
🥴
Oop
i just spoonfeeded
I don't understand nothing tbh
💀
It is?
unless its a mass ban like ban multiple members
well, what you need to do, is iterate through guilds that bot has
and then simply call .ban() on every of them
no its not, if bot has perms to ban lol
not sure
No because it's a private bot, only for the guilds i trust and give me permission to
morally wrong tbh
morally
and ^
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/...")
@verbal gulch so, if you don't understand things, you should probably go learn some python
OHH i understand now thanks ya
I just didn't understand the last thingy
what exactly
the
except HTTPException
I understand now. Thanks you
whats the pycord equivalent of created_at?
oh, okay
pycord also uses created_at
i'd suggest writing this code from scratch, so you understand everything, also, i didn't implement all the checks here, so
url buttons can't be created through decorator; you have to construct using discord.ui.Button
discord.ButtonStyle.url doesn't exist
can you give me a reference on how to do that please?
and that
no it does exist
at the bottom
but you don't need it since passing url forces it to that style
🤨
quite literally something like button = discord.ui.Button(label="...", url="...")
then add it to the view with add_item
it will be defaulted to url style if there is url kwarg iirc
yeah
would i need an \_\_init\_\_
o
oopsie
is ctx.message.created_at valid?
nope
would probably be easier if it did
then you can create the button inside the init and do self.add_item
:class:`datetime.datetime`: The message's creation time in UTC.```
tytytyty

how do i make an arg optional?
default it to something
so in the function def i should do like
or, if you are speaking about slash commands, there is required kwarg
yes, slash commands
you should default an arg to None (idk if it still works) or use discord.Option(required=False)
try it out, if it works
also, i think you should specify the type of arg
im pretty sure its needed
comment out slash command and run. uncomment and run
because pycord doesn't update commands?
if you don't specify it will default to string
pycord did update them but idk which pr in 2.0 broke it lol
it's perfectly fine on rc1
but where is that even being cached that i need to reset it?? the API?
discord stores slash commands themselves
ohhhh
interesting
i should probably still set a type and a name and stuff on the arg, how do i do that?
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
How do i reply to private messages on discord py?
go to discord.py then. but it's just message.reply
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
ok thank you
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'
you can't
you have to directly response with a modal
and you can't send another modal if a modal was received
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?
you may have restarted your bot to where it reached that limit even tho you only have 56 application commands.
mhmm okay and how i can use edit_message ?
await interaction.response.edit_message("ss") is not works because i have already send
How can I use slash commands sub groups in multiple cogs?
which timeout function
use member.timeout_for
https://docs.pycord.dev/en/master/api.html#discord.Member.timeout_for
elaborate
no, just make a timedelta object
it's explained at https://docs.python.org/3/library/datetime.html#datetime.timedelta
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.
hold on
Ok.
use bot.get_application_command(name, type=discord.SlashCommandGroup)
https://docs.pycord.dev/en/master/api.html#discord.Bot.get_application_command
I'll try that, thanks!
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!")
whats the issue here? with no traceback we have no idea what's going on
Why does this not work?
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
?tag codeblock
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.")
?tag idw
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.
This is a giveaway command, but when I type "!giveaway 13 test" nothing is sent? Can you check if I typed it wrong?
?tag intents
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)
you need the message_content intent for prefixed commands
then is an error message?
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
read the intents tag i sent above
Please read this https://guide.pycord.dev/popular-topics/intents
All about intents in Discord.
is it possible to edit a modal while a user is on it for live input validation?
i have
your code will not work
you have to set the message_content intent to true and add it to the bots intents
nope
use str instead of discord.SlashCommandOptionType.string
what should i use for options then
(and that or string you have won't work at all, use the choices arg instead https://docs.pycord.dev/en/master/api.html#discord.Option.choices)
first time using choices so a bit rusty
no, literally discord.Option(str, ...)
what's discord.SlashCommandOptionType.string for then
it's used internally, you don't need it at all
ah right
what's your code, and did you specify the message_content intent?
Is it possible to get the subgroup of the slash command group?
what would i put for the autocomplete arg
subgroups are under the same type
It returns None when I try to get the subgroup.
hmm hold on
Ok.
autocomplete is only needed if you have a lot of options the user needs to search through
for the code you provided, if you only need three set options then just use choices = [...], passing in a list of choices
what if you remove the type parameter
yes i was thinking of choices rather than autocomplete, thanks
It returns None as well.
what about type=discord.ApplicationCommand?
that should capture all types of commands
hold on I'll try that.
oh i see
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
I'll try that.
It doesn't return None anymore, however, how can I now use it to make a new command with it?
I tried
grp = get(self.client.get_application_command("event", type = discord.SlashCommandGroup).subcommands, name = "config")
@grp.command()
...
but that didn't work.
just checking, config is a group?
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
How can I do that? Any suggestions?
wait so what are you trying to do
I created a subgroup in a cog, and now I'm trying to use the same subgroup from another cog.
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
hahaha yeah that's simpler than i was expecting
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
Alright. I'll try that.
otherwise i think you'd be better off just doing it in the same cog
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.
Anyway, I'll try this.
that won't work because you can't access self there so it'd break
I see.
also in load_extension make sure you have store=False so errors will show
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.
is it ok to always have store=False? or just when debugging?
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
so what's the difference other than showing errors?
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
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.
can you show the code anyway
btw @cyan quail, thanks for the help yesterday. I forgot to thank you.
you should probably subclass the bot and use self for variables instead
though bots already have internal command lists
Much more cumbersome to set up my cogs, no?
Yeah, but I display my command list on my website, so I like to have it display from one source
cog creation is also a form of subclassing
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
use client.all_commands
there's a basic example at https://guide.pycord.dev/popular-topics/subclassing-bots/
Yeah, but I'd have to update it each time I finish developing an update on my bot
ah so your command_list is manually formed?
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
Cool, I'll check it out - thanks.
then come this error..
await interaction.followup.edit_message(view=Ticket())
TypeError: Webhook.edit_message() missing 1 required positional argument: 'message_id'
how about interaction.edit_original_message
Do I subclass commands.Bot or discord.Client?
whatever you normally use
I'm using commands.Bot, so I'll use that then.
yeah this is works thanks for helping me 
allgood
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()
?
that's just python
And it'll fire like normally?
yeah
Cool.
give it a try on a test setup if necessary
👍 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__(...)
what is the snowflake meaning there exactly?
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
I believe you have to supply a list of messages you wish to delete
How can I use @bot.check when subclassing a bot?
yes fetching the messages
messages = await channel.history(limit=limit)
TypeError: object HistoryIterator can't be used in 'await' expression
nvm flatten
works
yeah that'd be right
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?
Ah, but that'd be on a cog-by-cog basis?
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
bulk (bool) – If True, use bulk delete. Setting this to False is useful for mass-deleting a bot’s own messages without Permissions.manage_messages. When True, will fall back to single delete if messages are older than two weeks.
just check message.created_at inside your check function
oh awesome
So would it be @commands.Cog.bot_check? (for the decorator)
i think @discord.Cog.bot_check
But it's inside a cog?
not necessarily
I'm using it inside a cog
yo
does anyone know the docs link for custom bot status?
it's like how we use commands.Cog.listener
i guess maybe commands.Cog.bot_check then but either should work
discord.Cog doesn't exist, so I don't think it could be that
it does
"Cog" is not a known member of module
cogs are no longer exclusive to the commands extension
Ah ok
maybe you're on an older version? it definitely exists
what is it
and it doesn't work without self either?
oops wrong reply
don't think bots can set a custom status, at most you can use change_presence https://docs.pycord.dev/en/master/api.html#discord.Client.change_presence
i mean async def check_command_safety(ctx)
then no (self) on decorator
or maybe
could you try just ctx, without typehinting
Is this even a decorator? The docs refer to it as a method
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}")
i did it
but can't set status that change itself after a certain ammount of time
?tag oop
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.
ok wow im bad
just define bot_check anywhere inside the cog and it should work
likewise, Guild is a class
i tryed myself basic python but something got wrong
elaborate?
please don't use a while loop for this
so i take you want to change the status every few minutes?
i recommend using the tasks extension https://docs.pycord.dev/en/master/ext/tasks/ a few examples there
oh alright
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
what discord.__version__ and code
ohh
there was an api change to how guild.bans works
lemme see
about the buttons i still dont know
oh u mean pycord version
v2
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how can i pull all the banned members from the guild without specifying the limit
maybe just use a big limit
i will just go with default
still worried about this tho
so none will get all of them right?
yes
awesome
can u check the button thingy?
they work but still says some fail issue when clicking
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
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
ohhh
am i using that? idk i didn't update this code for a long time... it used to work
nah that's fine, ignore me
i mean last change yesterday.. black format
thanks nelo
it works very well now haha
oh about the ban members new changes
i see it works a bit more different... how could i get how many users are banned
like enumerate them
so then just get the length of it
awesome
worked
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?
you are doing something wrong.. probably pulling an entire list and it just wont fit in the embed field
your seeing all the code
look what happens when you print(ctx.guild.roles)
check the length of it
how.?
it's a list....
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
like u did for the others
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!")
because bot literally isn't defined in your view
inside a callback, you can access bot with interaction.client
it wont give any outputs error
ty
lemme see where the code stops cuz idk lol
you might need to defer if you're using guild.bans
also you really don't need to do that
it will just stop before the if statement
then banentry.user was none
but again, this is very inefficient
just use fetch_ban to fetch a single ban https://docs.pycord.dev/en/master/api.html#discord.Guild.fetch_ban
it will raise an error if the user isn't banned
i mean im using the ID
that's why i have the user as a int parameter
and then im checking the user id
get a user object with get_or_fetch_user https://docs.pycord.dev/en/master/api.html#discord.Client.get_or_fetch_user
also i might be wrong, but i don't think int will accept user IDs?
it worked before api changes honestly
using discord.User will automatically convert the ID to user though
does it? so its better than int?
dosen't work
same with other types like Member, Role, TextChannel; they all accept IDs
oh
len(ctx.guild.roles)
imma try this
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
well yeah you can just iterate through guild.bans
cause that would be just better tbh
you could do it in autocomplete but be very careful
what do u mean 
if you just stick guild.bans in autocomplete you'll be ratelimited to hell and back
not again 😂
``` why isn't these hyperlinks when i send the embed?
can you show a screenshot
How do I access my bots avatar via using interaction.client?
client.user.avatar
ty
or display_avatar if it isnt set
display_avatar caused errors for me
Just making sure, would this return a url?
avatar.url
you forgot {} around your variables
hm, I have interaction.client.display_avatar.url rn and it says 'Bot' object has no attribute 'display_avatar'
you're missing user
replied to the wrong message
you need client.user
ooo okay ty
how do you get a guild boost level?
guild.premium_tier
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)
joined[:-1] removes the last letter
you might want just {joined}
ty very much :)
np
i think its because its still text and not a url? might be wrong
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
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?
definitely
vs code is a code editor
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?
author.roles is a list of role objects
so a set with the author's name is never going to be in it
but it is a role named “har”
author.roles is a list of role objects
that worked tysm
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 😂
just put them in a list and return it
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 ?
can i create a vps host for more than a single bot?
yes
as long as its powerful enough (which almost anyone should be) you can run multiple
np
annoyingly you can't combine discord.Member with autocomplete so it would just be whatever string you put in the list
I run like 5 bots all in docker on one host
4 cpus and 8 gb of ram
probably overkill tbh
they're all in one server each and most of them are barely used 😄
only two are really used a lot
banned_users = []
async def get_autocomplete(ctx: discord.AutocompleteContext):
async for ban in ctx.guild.bans(limit=None):
banned_users.append(ban)
put the list in the method
will this way work?
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
why?
looking at it ctx is using discord autocomplete context
i don't know just saying lol
i will try and let u know...
try it
try using get_guild with ctx.guild_id
sorry what?
also because guild.bans is an asynciterator you can use .flatten with it
ctx.bot.get_guild with ctx.guild_id
ctx.interaction.guild
i didn't know i could use get_guild
did you forget to await?
what's None?
so do some debugging to find out what's None
and please just send your code and errors as text
sorry im just being so fucked rn
exactly, it's hard to see what's wrong without the full error
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
cut out most of the code, and start adding it piece by piece and when you get an error tackle it then
maybe make a new thread too
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
general help is really for quick single issues
you have lots of issues so you should have your own post 😄
just make a new post and put your code and full stack trace there
#969574202413838426
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
.
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
so what's the issue?
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
what did i forgot to await before? i forgot
idk
i also got #1006723806641016843 if u wanna help lol
Is it possible to change the slash command defaults in the bot integration?
wdym defaults?
These, in the integration settings
Like when a bot joins a new server for example, a certain command will be disabled for @e
ah right, I'm pretty sure it is using decorators
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
does anyone know why i get this error when i try to pip install psycopg2-binary in my project's venv? https://hastebin.com/ubodihucel.sql
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
installed https://postgresapp.com/ and it still fails to install
does the environment have libpq-dev (or postgresql-devel for centos/fedora) installed ?
or check if postgres.app bundled pg_config with it as well
One message removed from a suspended account.
Could you send your code please?
One message removed from a suspended account.
One message removed from a suspended account.
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
One message removed from a suspended account.
b!rtfm pyc followup.send_modal
No results found when searching for followup.send_modal in pyc
yeah you can’t follow up a modal interaction
One message removed from a suspended account.
One message removed from a suspended account.
b!rtfm pyc followup.edit_message
No results found when searching for followup.edit_message in pyc
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
One message removed from a suspended account.
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
data['options'] has the values of the parameters
does interaction_check get called before any of the button callbacks?
are snowflakes guaranteed to be sorted by creation date?
nope it does not, it isnt in the data dict
¯_(ツ)_/¯
im surprised this isnt possible as the discord client shows what options they used
Is that everything in data?
yes
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)
Yes you just need a persistent view
So it’d work after a bot restart as well?
Who compare reactions with str?
like this? if reaction == ":one_stars:":
read your error
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}')
Same callback name
that was easier than I thought, thank you
yes
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
How can I get all messages from a channel?
MessageInteraction payloads don't carry this info https://discord.com/developers/docs/interactions/receiving-and-responding#message-interaction-object-message-interaction-structure
You'd have to use the original ctx.options
I do this:
async for message in channel.history(limit=None):
But I have this error:
AttributeError: 'TextChannel' object has no attribute 'news'
update your pycord
How?
uninstall py-cord and install py-cord==2.0.0
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:```
what code
async for message in channel.history(limit=None):
But If I change limit=None to limit=200 its working
it's because limit=None takes a long time
especially if the channel has more messages
you need to await ctx.defer() before that
Thnks bro
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
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?
you can do it with the os.listdir() module
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
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
if you make sure they're images or just dont evaluate them as anything but images you should be fine
Anyone have a bot with SlashCommandGroup?
yeah why
there can be a gap in security there still though, but there shouldn't be unless another exploit is discovered or smth
I dont know that is it xd
.
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
there are examples with SlashCommandGroup here
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
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?
your autocomplete might exceed the max length of items
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
my select interaction is failed.
i edit original message in select, and it's my response, but discord send me interaction failed
dont forget to super init
Thaaanks
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
i'd like to know too
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.
I see there's two methods to generate a snowflake, does it matter which one I use? I just need to use it as a sort key in a database
Not really; the level of random is more than enough for it to not matter.
time_snowflake is useful if you want it at a specific time, but generate_snowflake is easier if you just need one representing now
You don't need to defer because you already responded to the command
but after they confirm the request can take longer than 5 minutes
Deferring is only necessary if the initial response will take longer than 3 seconds
Right so it doesnt matter how long the response takes?
Probably not
Just give it a try I guess
(Also if you're doing confirmations, buttons are far nicer)
thanks!
does someone have a tutorial for playing audio in pycord?
i've sort of done it
but now im getting more errors

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
Hello, anyone know how to make a button work after restart?
Here's the persistent example.
Is there any way to check whether the bot can DM a user without actually sending them a message first? Ping on reply please
Doesnt seem to work. If its longer than 3 minutes it just wont respond after that.
I use requests.get() and make sure the file extension is of an image e.g .png, shoud that be alright?


