#discord-bots
1 messages Β· Page 388 of 1
How can I reduce Memory usage on my discord bot its in 1,040 guilds
Disabling caches that you do not need as an option. IE if you do not need to use get_member often you can disable the member cache
I believe that is a Bot argument
How can I disable it?
!d discord.Intents.members
Whether guild member related events are enabled.
This corresponds to the following events...
disable this intent
but i think I need it
how?
https://discordpy.readthedocs.io/en/stable/api.html?highlight=client#discord.Client
member_cache_flags can allow for control over how much you need
even if you still use it
max_messages is another option but generally you dont want to disable it entirely
wdym control?
Im not sure, I just know there are settings you can changes to not entirely disable it but to make it take up less memory. You can find more on the docs. I have not personally used it just have seen it mentioned
Yeah but like what does max_messages do?
like how many max messages the bot can read?
you pass an int to denote how much messages to cache at the same time
It changes how many messages the bot is allowed to store in cache. It is set to 1000 by default
e.g 1000, only 1000 messages will be cached, if another message is cached the oldest is removed to make space for the new message
It will most likely not have as much of an impact as doing stuff with members as the member counts will be much greater than 1000
is this an int too?
No, the docs show the object that you have to pass to it which i think is just a group of settings
also
how can I shard my discord bot
also
I get 2024-09-06 17:02:58 WARNING discord.gateway WebSocket in shard ID 0 is ratelimited, waiting 21.70 seconds this all the time it sends it like 5-10 times
before the bot starts up
Also everytime I startup my bot
it shows this
server leave server: `````` owner: None
in my logs
Is it possible to allow tenor links to the discord's automod? For example triggering any other links but not the tenor gifs that discord uses.
regex = r"^(?!https:\/\/tenor\.com\/view\/[\w\-]+-gif-\d+).*" Tried this, but i receive an assertion error if i use ?! to handle negative lookahead...
Purpose:
- Triggering any links, excepting tenor gifs that discord has.
Don't think that's the right URL in the first place
Could be possible... was testing multiple ways...
When selecting a GIF and sending it, it's being sent via Discord's CDN
Example:
https://images-ext-1.discordapp.net/external/MzYSek_ukQ4R35_1oaFRRODFWUYHQ4YcHaKBXv5djR4/https/media.tenor.com/tNfwApVE9RAAAAPo/orange-cat-laughing.mp4
If you copy messages, yes, it will be attached to discord, but when sent it will still be a tenor gif
or just client sided i guess
it's an emoji
you sure? i tried it using the default one
it's probably a custom emoji
this is a channel select
!d discord.ui.ChannelSelect
class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.
Please note that if you use this in a private message with a user, no channels will be displayed to the user.
New in version 2\.1\.
datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
What else should I use? What's most common to use
as in the message, datetime.datetime.now(datetime.UTC).
discord.utils.utcnow exists
Which one is more recommended? datetime.datetime.now(datetime.UTC) vs discord.utils.utcnow
they do the same thing https://github.com/Rapptz/discord.py/blob/master/discord/utils.py#L781
discord/utils.py line 781
return datetime.datetime.now(datetime.timezone.utc)```
they're functionally the same but the former is more common so it's obvious to a reader what it does at a glance (without having to look at documentation or reference)
is .utcnow() not obvious
i feel like it could be confused with the deprecated datetime.datetime.utcnow()
Β―_(γ)_/Β―
Thanks guys
Is there any easier way to do this?
await self.counter_collection.find_one_and_update(
{"_id": "case_counter"},
{"$inc": {"count": 1}}
)
counter_doc = await self.counter_collection.find_one({"_id": "case_counter"})
return counter_doc["count"]
I want to avoid importing ReturnDocument from pymongo
If possible
So that I can solely relay on AsyncIOMotorClient
i'm not seeing where pymongo.ReturnDocument is being used
Well this is what I'm using currently
async def get_case_id(self):
counter_doc = await self.counter_collection.find_one_and_update(
{"_id": "case_counter"},
{"$inc": {"count": 1}},
return_document=ReturnDocument.AFTER
)
return counter_doc["count"]
i don't see a way around it if you need that field
Do you have any idea how I can add exceptions for the database calls? @sick birch
I'm using AsyncIOMotorClient
this seems out of scope for this channel, not sure i can help as i don't use mongo. sorry
Uhm get_guild and fetch_guild will only get the guild where the bot is in right?
ye
So looking through this there seems to be an issue with annotation. I have looked at it and do not see anything that's different from any other of my files I've rewritten the annotation but still unable to figure out what's causing the error. Any thoughts?
It's at the bottom of the code
slash commands requires you to set a typehint on your arguments, on line 16, your args is not typehinted
How do i get the selected option in a SelectMenu?
!d discord.ui.Select.value
No documentation found for the requested symbol.
property values```
A list of values that have been selected by the user.
how do i know what is the latest one
the values will always be the latest one, it gets updated as soon as it gets a new data
oh
so i cant access the info of guild the bot isnt joined?
Does not caching my members mess around with like GET member and stuff like that
nop
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
That's sad
im getting ```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: This field is required
from this select class
```py
class Select(ui.Select):
def __init__(self, bot: commands.Bot):
super().__init__(
placeholder='test',
options=[
discord.SelectOption(label=i)
for i, v in bot.cogs.items()
]
)
self.bot = bot
what could be the issue?
You sure that bot.cogs dict isn't empty?
That means you're missing a field, (can't be empty)
yes
How?
what is a field?
Ensure that bot.cogs.items() is returning valid items.
yes its valid i checked it before
I doubt if you get that issue
class Select(ui.Select):
def __init__(self, bot: commands.Bot):
options = [
discord.SelectOption(label=i)
for i, v in bot.cogs.items()
]
if not options: # Ensure there is at least one option
options = [discord.SelectOption(label='No cogs available')]
super().__init__(
placeholder='test',
options=options
)
self.bot = bot
Still, bot.cogs.items() will return empty
options = [...] or [discord.SelectOption(...)] works too
and also make sure that there is at least one option in the Select component.
Yeah, just an example to ensure there's always 1
Won't fix they're issue, because bot.cogs.items() will be empty
That's what causes the HTTPException
Also i don't really like d.py, how they work with views, i prefer disnake.
That's what that does
Fallback to a list with one entry if the other list is falsey (empty)
Yeah but if bot.cogs.items() it's empty still won't fix they're issue
Yeah, i understood, and you're right.
.
That was a fallback example to ensure there's atleast 1 option
Fair
I believe they are trying to get they're cogs?
The class is either somehow constructed before any cogs are added or they aren't using cogs yes
print(bot.cogs.items())
@mint pecan
bot.cogs returns a empty dict in the class but in other scope it does return a dict with cogs
How and where is that class constructed?
i just make a view and add the selectmenu to the view then send a message with the view included
It's obvious already, ensure that bog.cogs.items() it's not empty, i cannot help you with your internal code, we don't know it.
Where exactly?
Maybe just send that code
Oh, was the bot completely up? This could be a issue if you invoke the command before the bot being run
bot initialaztion
And where do you load your extensions?
setup hook
Is this class constructed before or after that?
class Select(ui.Select):
def __init__(self, bot: commands.Bot):
# only set placeholder here, leave options empty for now
super().__init__(placeholder='test', options=[])
self.bot = bot
async def callback(self, interaction: discord.Interaction):
# this will be called when the menu is interacted with.
# lazily load options only when needed
self.options = [
discord.SelectOption(label=i)
for i, v in self.bot.cogs.items()
]
if not self.options: # handle the case if no cogs are loaded
self.options = [discord.SelectOption(label='No cogs available')]
# now do something with the interaction and options
await interaction.response.send_message(f'Selected cog: {self.values[0]}')
before, but i also tried to put it on on_ready and it does the same
Mayhe construct it after the extensions are loaded?
how do i know its loaded
Why is at bot init anyways
@bot.event
async def on_ready():
print(f"Bot is ready! Cogs loaded: {bot.cogs.keys()}")
After the loop ig?
for x in y:
...
# y is all iterated through
simplify with on ready event π
They need to construct the class after, not print something
they said this
And on_ready shouldn't be used for that anyways
As it can be called multiple times and while running
????
How so?
Because i asked this #discord-bots message
Read the docs
discord can call the event multiple times
How is on_ready running multiple times?
Welp
snipy here
I just said why?

tl;dr discord can disconnect your bot and the library have reconnection logic, on_ready could be called again in that context
Ahhhh, but never against this lol
if you want something that is called only once you should use setup_hook (d.py) or in disnake you can subclass the client that you are using and edit the start method to call a custom made method
You know i use disnake π
And it's not me having issue here, it's @mint pecan with cogs, but they use d.py
or if you don't use .run you just need to call it in your main.py
^^
Thank you Snipy whoever you are that they trusted you over me lol
Cause we friends π
Aha
I didn't know this on_ready thing, never happened to log multiple twice on run
eitherway, we don't do actions on_ready, task util ready
on_ready has just a log info
So i still don't see this being a issue
Says just client is ready, that's it
Sure it's not an issue for you
But most people load their exts etc in it which can lead to errors
and he said this^
Doesn't mean they have to keep the event
Oh i didn't ready π
They might construct the view in on_ready because you said that
@mint pecan Hope you didn't understand that from my context, on_ready shouldn't be used for any actions.
It can be used for some actions, you just need to be aware of the fact that it's potentially not called once (and so don't rely on that)
Or an if-statement with a botvar etc yes
i clean db entries like that
Same
I use txt files as db... we're not the same π₯± /j
π
100% sure you remember, but don't burn your memory
Absolute π moment
π
/j = joking
at least use json /s
lies! π
well i got another error when i try to pass the bot class
AttributeError: 'ProactorEventLoop' object has no attribute '_closed'
bot.help_command = views.HelpCommand(bot)
class HelpCommand(commands.MinimalHelpCommand):
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
async def send_pages(self) -> None:
select = ui.View()
select.add_item(Select(self.bot))
await self.get_destination().send(view=select)
class Select(ui.Select):
def __init__(self, bot: commands.Bot):
print(bot.cogs)
print(bot)
super().__init__(
placeholder='test',
options=[
discord.SelectOption(label=i)
for i, v in bot.cogs.items()
]
)
self.bot = bot
Pretty sure it means "just better" /j
lmfao
Why are you even printing the bot?
i forgot to clean it up
Uh don't do that anyways
I am pretty sure the issue doesn't come from this
You can access your bot from self.context.bot
The help command class takes some options and that'll cause issues when the lib tries to construct it
tldr: remove the __init__
could you share the full traceback?
i tried to remove the bot parameter from the helpcommand class and the error disappeared
It's a atr error from ProactorEventLoop, I don't even see it there
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Exception ignored in: <function BaseEventLoop.__del__ at 0x0000014F9CE9D620>
Traceback (most recent call last):
File "D:\Python\Python312\Lib\asyncio\base_events.py", line 725, in __del__
if not self.is_closed():
^^^^^^^^^^^^^^^^
File "D:\Python\Python312\Lib\asyncio\base_events.py", line 722, in is_closed
return self._closed
^^^^^^^^^^^^
AttributeError: 'ProactorEventLoop' object has no attribute '_closed'
ig they use ProactorEventLoop._closed somewhere, but it doesn't have an atr for closed
yep
Windows stuff and fixed in 3.12 or something iirc
bro stop yapping, that's asyncio internals
ππ
that's what atr error says π
Doesn't matter anyways 
holy shit bro this solved all the errors tysm
Is it possible to allow tenor links to the discord's automod? For example triggering any other links but not the tenor gifs that discord uses.
regex = r"^(?!https:\/\/tenor\.com\/view\/[\w\-]+-gif-\d+).*" Tried this, but i receive an assertion error if i use ?! to handle negative lookahead...
Purpose:
- Triggering any links, excepting tenor gifs that discord has.
@timber dragon Do you know anything about this?
discord doesn't allow ?! chars for negative lookahead :/
crap
nobody knows π
Have you tried the disnake server?
I know regex a little bit but not discord's automod
Yeh, snipy replied, but it's not even that related to disnake... it's what discord supports...
Bruh
but snipy doesn't know for sure what discord accepts as regexes
I did open a post there now, hoping to get a proper reply, if someone knows how to make a negative lookahead over tenor...
Discord devs server? .gg/discord-developers
I did not try there
I am not in that server from this acc, Can you send me a invite in dms?

https://discord.com/channels/613425648685547541/1281942203303985204 damn someone responded immediately
Yeah... not the asnwer i expected...
But it's a way to bypass still
to not use regex
had hope this could of been done with regex π
just realised it wont fix this issue
nvm
what they suggested is still regex, the solution you were looking for could have been overcomplicated
They said blocked words...
regexing words, not an actual regex handling them all, with just 1 regex... But yeah, i tested it does work
Isn't that what none is supposed to be?
that's just a default value
you may want str | None ? also i think you didn't got app commands quite right, they can't accept any arbitrary number of arguments (like prefixed commands) you need to define every single argument that you need in the signature, you could make some of them optional tho
When doing a User invite , for a discord bot. Is it pretty much just an automation tool for a discord account ?
wdym?
So I need to add str = None
most likely a union str | None or Union[str, None]
read the other part tho
I did. These commands are nowhere near done. I'm in the process of converting them from a generalized prefix over app commands
I see
That goes up next to the args = None correct?
What is wrong?
# Decorator to check if the action (warn, ban, kick, etc.) can be performed.
def check_actionable(self, action_type: str):
def decorator(func):
@wraps(func)
async def wrapper(ctx, member: discord.User = None, *args, **kwargs):
if member.id == ctx.author.id:
await ctx.send(f"{self.x_emoji} You cannot {action_type} yourself.")
return
if member.bot:
await ctx.send(f"{self.x_emoji} You cannot {action_type} a bot.")
return
return await func(ctx, member, *args, **kwargs)
return wrapper
return decorator
# Warn command
@commands.command(name="warn", description="Warn a user.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
@check_actionable("warn")
async def warn(self, ctx, member: discord.User = None, *, reason: str = None):```
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: Moderation.check_actionable() missing 1 required positional argument: 'action_type'
yes
args: str | None = None
Okay I see what I did now wrong. Thank you
thanks! however, i cant define the channels that i want to put in there? or how do i do that?
you can't, use a string select for that
then how do i get that beautiful # like i showed u yesterday?
for string selects you can't, that's how the discord client displays channels for channel selects
you could try to find a custom emoji similar to that
i think that the menu i showed u isnt a channel select bc it only shows hiring/hireable channels rather than all channels
import random
import os
def get_response(message: str) -> str:
person_message = message.lower()
if "website" in person_message:
return "**Official airpodgate site [censored for privacy] **"
if "buy" in person_message:
return "**you can purchase by opening a ticket or visiting [censored for privacy]**"
async def send_message(message, user_message, is_private):
try:
response = get_response(user_message)
await message.author.send(
response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
TOKEN = 'no peaking'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(client.user, "is now running!")
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
hey everyone this is my current bot for my server -- I have two questions, first how can I make it so it only sends the message if I say it? and second how do I make it link to a chanel, I tried to do #buy (which is a valid chanel in my server), but it didn't work
You can limit what types of channels will show but not what specific channels will show
https://discord.com/developers/docs/resources/channel#channel-object-channel-types
You can check if message.author.id is the same as your user ID
Also you can mention a channel like this #discord-bots [#discord-bots](/guild/267624335836053506/channel/343944376055103488/) where that is the channel ID.
Also in general you should probably use discord.ext.commands for creating commands instead of processing the string yourself but if this is just a small project that is up to you if you do not want to bother.
you can obtain the channel id from message from message.channel.id
I apperciate it bro
link to a chanel
They do not want the same channel as the message
something like this or am I doing it wrong
umm, how many language you mixed together?
other than your syntax being wrong yes
I normally code in c# so that might explain it
like this?
- don't use parenthesis
- id are ints
- no colon after return
1273475167976423577
do you have developer mode on discord?
here you go
no how do you turn that on?
you would go to Setting -> Advanced -> Developer Mode
and set it on
This article explains it all
1273475167976423577
and right click on your user and click copy id
i got it thanks
tbf, where the colon come after return come from (I mean which programming language
how do i return the message id of a message i sent?
await interaction.response.send_message(content=":clock3: Denying post...", ephemeral=True)
context: message after hitting submit on a modal
no idea I just don't know how to code in python assumed you do it like that
you would get the message for the send statement and get the message id
this doesn't seem to be working -- I keep getting the error "'str' object has no attribute 'author'" does anyone mind helping me
how tho? i am trying to put it in a variable but the variable stays "None"
waitmessage = await interaction.response.send_message(content="π Denying post...", ephemeral=True)
send_message doesn't return a Message
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
The message that sent this interaction.
This is only available for InteractionType.component interactions.
doesn't seem to show how to get id
or that
damn im stupid lol i cna just edit original response since i didnt defer
any help, sorry for bumping it
did you re-assign message to anything else?
no
is message discord.Message?
this doesn't work in OOP
import random
import os
def get_response(message: str) -> str:
person_message = message.lower()
if "website" in person_message:
return "**Official airpodgate site [privacy]**"
if "buy" in person_message:
return "**you can purchase by opening a ticket at #buy or visiting [privacy]**"
if "exec vendor" in person_message:
if message.author.id == 1273475167976423577:
return "test"
async def send_message(message, user_message, is_private):
try:
response = get_response(user_message)
await message.author.send(
response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
TOKEN = 'no peaking'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(client.user, "is now running!")
@client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)```
message: str
wdym?
it is not discord.Message, so obviously you cannot
oh I see
look at line6
also, would really recommend looking into commands framework if you're looking to create commands instead of doing all of the logic yourself
nah because I don't want it to be a command
?
I own a server and a lot of people have issues I guess reading on how to buy -- so when they say "how do I buy" or something like that then the bot guides them there
but it is already a command
ah
no sorry, you might be confused -- I don't want it to be a command I just want it to reply if they say something
yeah -- so wait what exactly am I doing wrong so I learn for the future
give discord.Message to the function, not str
so
def get_response(message: discord.Message) -> str:
person_message = message.lower()
or def get_response(message: discord.Message) -> discord.Message:
person_message = message.lower()
When your inviting/ adding a bot thereβs an option between guild invite or user invite
it is not automation tool for a discord account, it is just you are able to use the bot user installable slash command in anywhere, even if it is in other people dm/group or server without the bot
*ignore the dm/group part, it is not possible actually
it should be, you just have to explicitly set it in your command's allowed contexts
is it possible to append a parameter in a command to the command's check parameters?
for illustration, this is my command's code:
@commands.command()
@has_profile()
async def profile(self, ctx, member: disnake.Member = None):
and this is my check's code:
def has_profile():
async def predicate(ctx, member: disnake.Member = None):
member = member or ctx.author
data = PROFILES.find_one({"_id": str(member.id)})
if not data:
raise NoProfileFound(member)
else:
return True
return check(predicate)
Apparently, the member in the command's parameter isn't passed to the check, so it returns member as None which is default. I want to pass the member passed in the command to the check.
!d discord.ext.commands.Context.args you can use this to access the member object that was passed to the command
The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.
Well, isn't the only allow additional context user_install (then the default context)? that work for me in other server/the bot pm, but not other pm/group
er, there are two types of contexts, installation contexts and interaction contexts
https://discord.com/developers/docs/interactions/application-commands#contexts
in the case of d.py, they're available with the slightly confusing names @allowed_contexts() and @allowed_installs()
you need both the PRIVATE_CHANNEL interaction context and the USER_INSTALL installation context for a command to be available in other DMs, after being user-installed
hmm
but:
By default,
contextsincludes all interaction context types.
Need to check if dpy feature the toggle of options
ergh, the discord API docs are incorrect
i made an issue for it a couple weeks ago discord/discord-api-docs#7108
@discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)```
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2\.4\.
Examples...
lol
from my testing the defaults were always GUILDS + BOT_DM and GUILD_INSTALL
Gonna fix my bot later and sync later
if I remember
(Would be trolling if you can use anywhere except bot dm
the CommandTree can let you assign defaults for all commands via the allowed_contexts= and allowed_installs= parameters, though if you use a plain commands.Bot you'll have to assign to the attributes instead, which are technically undocumented
Still just gonna use the decorator, too lazy
that what I do for user_install anyway
hope they fix the feature instead of fixing the docs, but well
How can i host discord bot in phone anyone can help me?
not a good idea
can I host a discord bot for free ?
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
no, free services have limitations so get a vps for like $2 a month and you're good
how many bots can I host w that ?
one or more
how to level up so that i can talk in vc
depends the bots, servers, intents, etc.
by talking
oh
talking here ?
anywhere in the server
but no one is active here
because it's a topical help channel, and there are not people needing help 24/7
#python-discussion, #ot1-perplexing-regexing and #ot2-never-nesterβs-nightmare are usually active
wouldn't be here if not
I am newbie π¦
π
in development
hehe same
yea I can tell
development like what ?
do you know BASH
making any projects
scripting ?
app development , web development , ai deve. etc ?
we should only talk about discord bot related contents here
oh
not scripting anything with it, just using the normal commands
how much time it will take to learn BASH ?
for kali linux
few days, as you can't do much with it
i mostly have seen it being used to automate the build and release of softwares
other than the basic commands e.g. ls etc. that are used every day by lots of people
!user
You are not allowed to use that command here. Please use the #bot-commands channel instead.
can somone help me to make a moderation discord bot
discloud is pretty good ig
does View class have an attribute where i can access the context/interaction?
no, that's only accessible from within a callback associated with that view
im getting TypeError: help_command must be a subclass of HelpCommand
trying to set custom help command
class HelpCommand(commands.MinimalHelpCommand):
...
bot = Bot(command_prefix=..., intents=..., help_command=HelpCommand)
how do i fix?
Can a bot read very long messages?
why not
it needs to be an instance, help_command=HelpCommand()
my selectmenu's callback succeeded but it still says "This interaction failed"?
How are you responding to the interaction? My guess it that you are sending a message instead of responding. Can you show your callback
i used interaction.message.edit
are you using discord.py?
yes
You need to use interaction.response.edit_message instead
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionResponse.edit_message
it fixed it thanks
since my query is complex i made a thread, but can anybody help me? #1282343500129501255
Doesnt this also require the original message id? so you'd also need to supply it with interaction.message.id?
pretty sure it does anyway.
It does not because the bot has this information cached
how can i interact with a button with python?
Like, i put in a message id and i interact with a button
0|bot | [2024-09-08 15:49:11] [WARNING ] discord.gateway: Shard ID 0 heartbeat blocked for more than 10 seconds.
0|bot | [2024-09-08 15:49:21] [WARNING ] discord.gateway: Shard ID 0 heartbeat blocked for more than 20 seconds.
0|bot | [2024-09-08 15:49:53] [WARNING ] discord.gateway: Can't keep up, shard ID 0 websocket is 32.5s behind.```
My bot didn't respond for maybe 30minutes I don't know why and I got these logs
I don't use time.sleep() or requests
my bot had uptime for 10 days and didn't face issues but got this for 3 days of uptime
could that be for joining vcs in loops, low ram?
from discord.ext import commands
from discord import FFmpegPCMAudio
intents = discord.Intents.all()
client = commands.Bot(command_prefix = "!", intents = intents)
@client.event()
async def on_ready():
print("Bot Is Running!")
@client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio("music.wav")
player = voice.play(source)
else:
await ctx.send("Error: Your aren't in a voice channel!")
@client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("Call Lefted")
else:
await ctx.send("Error: Im not in a call")
the bot joins the call but it doesnt play the music
i have client.run() btw but that includes the token so its not in there
hello i need help with my discord bot i have lot of issue when i try to make a whitelited command so only whitelited people can use the command i cant please help me and dm me or ping
It is better if you post your problem here or open a post in #1035199133436354600
Probably because duration_seconds is a string? Try print(type(duration_seconds)) if it's a straight number, then just do int(duration_seconds) > 1814400
Alright. Thanks. Wanna share with the class what the issue was?
It was actually from somewhere else in the code 
I thought so as the error didnt match the code itself. But I just woke up so I didn't want to pry too hard :D
with nextcord? looking through their docs it doesnt seem like they support setting interaction and installation contexts for slash commands yet, only in master branch
you can't install both libraries together, they share the same package and will overwrite each other's files
or more specifically nextcord comes with both a nextcord and discord package, the latter of which is a copy to help people with migrating from dpy to nextcord
Hello, your message has been deleted as it violates rule 6
And ethics 
How do i fix this guys my nothing is happening here
.rtfm
@swift siren #bot-commands
js tryna figure out smt
I wanna see the object for onboarding
member.flags.completed_onboarding
how do i fix this sorry im new
No such file
Happened to me when I used powershell instead of command prompt
Iβm not exactly sure what causes this, but powershell is said to be superior
You see PS written before your file path? You most likely want to get rid of that, click the + arrow on the terminal and select command prompt, that should work
no
powershell is better
Yup it is definitely better, I blame myself for not knowing it better
What do you recommend for this instance?
the issue is due to the file name not being correct
is there a bot.py file in the discordbot folder
and you can run all command prompt commands in power shell
Yup, for some reason, I still get this error as well when my file name is correctly existing in the respective directory but powershell doesnβt recognise it
can you send a screenshot of your file explorer inside that folder?
Not on pc atm π
yes
you should rename it to bot.py
then what should i work now
py bot.py should work
thanks
how do i check if a Command object is a group?
@bot.command()
async def check_command(ctx: commands.Context, command_name: str) -> None:
command = bot.get_command(command_name)
if isinstance(command, commands.Group):
await ctx.send(f"'{command_name}' is a group command")
else:
await ctx.send(f"'{command_name}' is a regular command")
Should be the same for d.py and disnake, idk what library you're using.
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
Can ctx.guild.icon.with_format('png').url be directly used as an emoji in Discord buttons?
I doubt, But why doing that when you can literally use the emoji format directly?
await ctx.send(
"Click this button!",
components=[
Button(style=ButtonStyle.primary, label="Guild Button", emoji="<:emoji_name:emoji_id>")
]
)
or <a:name:id> if emoji is animated
But you don't need animated
Won't work with animated, but letting you know that formats are similiar.
Itβs because I want to use the server icon as an emoji for the button, so it should be unique for each server
Why don't you upload the image to the server?
as emoji
I recommend uploading the emojis to the bot directly
What do you mean?
You literally upload the emoji, and just use it as set in the example, i don't find it overcomplicating.
No worries π
Well it becomes complicated when you have to do it for a lot of servers
Oh, i see your point now...
There is a way
1 moment.
Sure
Trying to make it up, i hope this will work
async def download_guild_icon(url: str) -> BytesIO | None:
"""Downloads the guild icon from the provided URL and returns the image data as BytesIO."""
async with aiohttp.ClientSession() as session:
response = await session.get(url)
if response.status == 200:
image_data = await response.read()
return BytesIO(image_data)
else:
print(f"Failed to download icon, status code: {response.status}")
return None
@bot.command()
async def converticon(ctx: commands.Context):
"""Converts the guild's icon into an emoji and uploads it to the guild."""
guild = ctx.guild
if not guild or not guild.icon:
await ctx.send("This guild either doesn't exist or has no icon set.")
return
icon_url = guild.icon.with_format('png').url
image_data = await download_guild_icon(icon_url)
if image_data:
try:
emoji_name = "guildicon"
emoji = await guild.create_custom_emoji(name=emoji_name, image=image_data.getvalue())
await ctx.send(f"Successfully created emoji: {emoji}")
# If created add emoji id to database, You can use the emoji that way, ensure your database in case emoji gets deleted.
except Exception as e:
await ctx.send(f"Failed to upload emoji: {e}")
else:
await ctx.send("Failed to download the guild icon.")
@young dagger
That is interesting. Thanks @dense scaffold
No worries !
How can I make discord.py use docstring in the callback as the description?
@bot.command(description="This will be desc")
async def greet(ctx: commands.Context):
"""Sends a greeting message."""
await ctx.send("Hello there!")
If your bot is interaction commands, to add description to options you can use for example:
async def example(self, inter: Whatever, user: Member, action: DefineAction) -> None:
"""This is command desc.
Parameters
----------
user: This will be user parameter desc.
action: This will be action parameter desc.
"""
@solar pollen
another spooky
There are two of them!
I know both of them
cool
π€£
C:\Python312\python.exe: can't open file 'C:\Users\Owner\.cursor-tutor\%USERPROFILE%\dylanrustbot\bot.py': [Errno 2] No such file or directory
PS C:\Users\Owner.cursor-tutor%USERPROFILE%\dylanrustbot>
how do i fix guys im new
i have the .py
The file is just called .py...?
i fixed that

but still not working
C:\Python312\python.exe: can't open file 'C:\Users\Owner\.cursor-tutor\%USERPROFILE%\dylanrustbot\bot.py': [Errno 2] No such file or directory
PS C:\Users\Owner.cursor-tutor%USERPROFILE%\dylanrustbot>
Are you sure you're on the right file path?
look i try to do and nothing happens
Also on visual studio code you can use run without debugging from the top of vsc app
Try this, and lmk if it works
And what is your code?
Use python debugger
Let's see if he runs it and it issues π
install the first one
i tried a new code and it turned on
So did it start the bot.py file you wanted?
using the vsc run button?
yea but i had to change my entire code for a test and it worked
That's great, Means your bot is running locally, keep in mind it will be stopped if you do ctrl + c in terminal, or when your pc turns off.
Let me know if you have further more issues.
alright thank so much
Hello everyone.
If you need any help with web and AI development, please feel free to contact me.
?!!?!
i tried both ways on a hybrid command and when i do command.description theres nothing
should be filled in command.help
what error we will get if we try to remove the user who isnt in thread?
or it will not give error?
Very quick try it and see exercise
You said docstrings, and after you do that, you need to restart discord app to refresh cache.
This way you can add description to your command
Hybrid*
Yes, that means prefixable and interaction too
The code you sent is not for hybrid command.
Was showing him a change on a previous code i sent
I know, it's previous code i sent, just showing how to do the description
^^
They didn't mention at first that this was for hybrid, bot logically it's the same.
To make it hybrid command you can change it to @bot.hybrid_command
That's a detail they can add, they didn't mention at first that the purpose was on hybrid commands.
^^^
This was what they said, and right after is my example.
Which is literally the same for hybrid, it's a 2 words change.
anyone care to help, i am trying to get my bot to respond when certain words are said, even in the middle of a sentence. i under stand the
"If message.content.startswith('Example'): "
But it only works is if it starts with the word, Any idea?
!e
you know you can do this
print("word" in "just a normal sentence containing your word")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
Regex would probably be useful to learn here
yeah or that too
Hello friends, I'm making a discord bot and I'm sure I'll have questions to ask. Just wanted to say hello there and hope yall are having a good day so far
hi

What is wrong?
elif any(message.guild.get_channel(message.channel.id) is None for message.channel.id in message.raw_channel_mentions):
modlog_message = "Posted an invite"
Tell us, what's the error?
Expected type 'collections.Iterable', got '() -> list[int]' instead
You need the [] around your list compression
Same
Then idk
traceback?
is there an option for the bot to pick from a list of options to reply to a word that is said?
yes
Do you know where i can learn to do it?
Expected type 'collections.Iterable', got '() -> list[int]' instead
That's an error message, not a traceback
Do you know how to solve this error?
I want to detect "#799641437645701151" these kind of messages that is not from the same guild
You should start by being able to get a traceback
Well I was trying to solve the error to begin with
You solve the error by getting the traceback
The library by default logs the traceback. Something you are doing is interfering with that
Ok i ran this, it shows no errors, but still does nothing when promted with "Hello" in discord.
i am still learning ish but i am not sure what i did wrong?
You should be getting a warning in your console
Sorry, This terminal?
How are you starting the bot?
visual studio code amt
In code
client.run('Tokencode')
thats how i keep starting it
then control C to stop it.
i had some basic stuff working this morning, but not it does nothing so i was curious.
You should be getting logs from the library
Can you send your full code? In text, preferably, not a screenshot
Also which library are you using?
import discord
import random
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True
client = discord.Client(intents=intents)
msg_list = [
'Hello! How can I help you today?',
'Good day! What can I do for you?',
'Hi there! Need any assistance?',
'Hey! Whatβs up?']
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if 'Hello' in message.content.lower():
response = random.choice(list)
await message.channel.send(list)
client.run('Token')
'Hello' would never be in the str.lower() right? It should be 'hello'
If you ran this code in dpy at least, you would get several logs in your console
i am not sure then, guess i screwed up somewhere.
?
its giving me no errors in any of my windows.
without sounding completely brain dead, What do you mean by library?
I was told the only thing i would need to do before doing anything is make sure i do this
import discord
import random
from discord.ext import commands
If you installed python fresh, it would not know what import discord means. You did something
(installed a library)
i installed python through MS store
Then installed visual
Then started the project
thats all i have done in means of prep
python does not ship with a discord module
Ok, so i would have to download the discord module?
i am assuming from discord developer page?
Someone already did on your installation if you aren't getting an error from import discord
You probably followed some steps you aren't remembering. Do you know what version of python you're running through vsc? Can you run python manually on a command line?
That doesn't necessarily mean that's what vsc is using
Hmmm
When you hit run on vsc, it runs some python executable
/AppData/Local/Microsoft/WindowsApps/python3.12.exe
thats the first thing that shows up when hitting run
Can you run that exact exe and pass -m pip freeze, then send the output here?
apparently not
-m pip freeze
File "<stdin>", line 1
-m pip freeze
^^^
SyntaxError: invalid syntax
Run it all in one line on command line
you're currently entering the python interpreter which you don't want
so exit() to get out of the interpreter, then on the command line .../python.exe -m pip freeze
exit()
^run that
it closes python
Now do the second part of this
It does, someone installed discord.py at some point (somewhat recently)
No, that's fine, but it's odd that you don't remember doing that
because this doesn't happen by default
my first time, im on bed rest and needed a hobby while i recover.
this hobby was suggested
It's fine, so you have discord.py installed, it should be giving you output. Do you know how to run the bot yourself via command line and not through vsc?
i do not, i was told vsc was the most friendly way to start this project.
Some part of your setup is eating all of the library's output, which is going to make any debugging difficult
You can look at that if you want to. The core issue why you aren't getting this code working is that your code is not requesting the message_content intent, which is required to receive message content. https://discordpy.readthedocs.io/en/latest/intents.html has a detailed description of that concept
Would i be better off deleting the project and starting again to clear the library's output? starting fresh if thats a thing?
It's probably something wonky with vsc to be honest. You could try running it on your own outside of vsc
But honestly I don't know how you'd get in that state
ah i see.
Maybe something in the output tab? 
Nothing again.
i will either try something else other than VSC or maybe move onto another project.
But Thank you for trying help figure this mess out.
Running it yourself is just going into the command line and doing .../python.exe <path/to/your/bot/file>
No traceback anymore. But I still see Expected type 'collections.Iterable', got '() -> list[int]' instead
elif any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
You need to get a traceback to effectively debug
again, it is something you are doing that is removing it
What do you mean removing it?
By default, when you hit an error the library will output the traceback
If you are not seeing a traceback, something in your code is interfering with that
It's a warning
So your code runs just fine?
So far yes
If I add the line somewere else I'm not seeing the error

this is the line of code with that warning?
Yes
can you paste a couple lines before and after for context
I can't use async def lfg_checks(self, message: discord.Message) -> bool:
The warning dissapears with async def lfg_checks(self, message):
that makes sense
it can't warn you anymore because it doesn't know what the types of anything are
But at the end of the function there is return True or return False
So it's excepting bool back
The message is a discord message
I don't see the problem
this is pycharm right?
Correct
In general, ide's complain about shit all the time, really up to you if it's worth making them happy
they use their own type checker which is known to be buggy at times
What's so special about any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
that particular line of code seems fine to me, i'd ignore the type error
maybe write some tests if you want to be sure
it's got a genexp, maybe pycharm type checker doesn't like that for whatever reason
Do you know how I could write the code differently?
this is readable and concise
i'd leave it be
i guess you could also do like, any(map(message.guild.get_channel, message.raw_channel_mentions))
to see if any of the mentions in the message are in your cache
This is the line it doesn't like message.raw_channel_mentions

this is a property
pycharm thinks its a method for whatever reason
Expected type 'Iterable[int]' (matched generic type 'Iterable[_T1]'), got '() -> list[int]' instead with your method
yeah it's the same thing there
Maybe I should just remove the type hinting
My goal was to create a 100% warning free bot
that makes it worse
By using async def message_checks(self, message): instead of self, message: discord.Message) -> bool
yes, now you can't type check anything in that function
the choice is obvious when it comes to not being able to type check anything in a function vs having one false warning (which can be ignored with a directive)
pycharm probably has some option to suppress warnings in the editor. i'd recommend running mypy or pyright for actual type checking in CI or whatever before going to production anyway
It actually disappears with async def message_checks(self, message) -> bool:
yes, because it can't type check anymore
that's not a fix
So specifying that the message is a discord.Message is a problem
no, it's not
there is no problem here beside pycharm itself
the code is fine, it will work, is readable and concise
i am not sure what more you want to do here
it's not a matter of integration with discord.py. all editors and type checkers have some quirk or another, there is no perfect system
personally i run neovim with pyright as my lsp, and also run pyright in CI so i don't get failed ci where it works locally
mypy by the PSF and pyright by microsoft are the two big ones
I'm running the exact same snippet of code on my other bot and not getting a warning message (the only difference is that the other bot is not using cogs)
Both in Pycharm
π€·ββοΈ like i mentioned pycharm type checker is known to be buggy at times
Sure
but why need to write code differently?
thought i would thank you again! i got it too work!
16 hours justifed for a noob such as myself.
Im trying to make a basic discord bot, but im probably having issues with permission. So i clicked the Admin general permission but there is no save button. What am i missing here?
looks like this is just a tool to calculate the permision integer, but where do i fit that in ?
I have experienced developers here, feel free to DM us anytime.
Glad to hear it 
again thank you! Also apologies for being a bit slow when trying understand what you was saying, brand new to this.
nw we all start somewhere, always feel free to ask questions
It should be part of the invite url but thatβs the old system, in the new one you can set the default invite perms
In the installation section
async def find_case(self, case_id: int) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
collections = {
"warnings_collection": self.warnings_collection,
"kicks_collection": self.kicks_collection,
"bans_collection": self.bans_collection,
"mutes_collection": self.mutes_collection,
"modnotes_collection": self.modnotes_collection,
}
for collection_name, collection in collections.items():
case = await collection.find_one({"case_id": case_id})
if case:
return case, collection_name
return None, None
Why am I getting Expected type 'tuple[dict[str, Any] | None, str | None]', got 'tuple[Mapping[str, Any], str]' instead
@sick birch Any idea about this one?
What type is case here?
Type of case: <class 'dict'>
Type of collection_name: <class 'str'>
Any idea?
Personally I don't bother trying to make type checkers happy 
Are you not using python 3.10.x+?
You could use dict built in instead of importing it.
And also instead of importing Optional, you could do X | Y for annotations
from typing import Mapping
async def find_case(self, case_id: int) -> tuple[Mapping[str, Any] | None, str | None]:
collections = {
"warnings_collection": self.warnings_collection,
"kicks_collection": self.kicks_collection,
"bans_collection": self.bans_collection,
"mutes_collection": self.mutes_collection,
"modnotes_collection": self.modnotes_collection,
}
for collection_name, collection in collections.items():
case = await collection.find_one({"case_id": case_id})
if case:
return case, collection_name
return None, None
This should resolve your issue.
I'm using Python 3.12
Even better, The code i sent uses proper annotations, There's no need to import Dict or Optional
You forgot to import Any 
But thank you
Apologies, imported Mapping cause that was the difference to fix your case.
Why mapping if I may ask?
Cause you were using Any already here.
Oh yeah you are right, I removed old code mb
It's suggested instead of dict, proper annotations for your case.
can i add aliases to a command's parameter?
how does a param have a name in the first place?
you can do similar thing with flags i wonder if i can do it with normal params too
Idts
I dont think I know what you mean, as far as I know normal params for text commands are purely named in the code and arent used when running the command
They can be used for flags
but they said with normal ones
what does that mean?
I dont think so
Aliases are for things users type in. If they're not typing in the parameter name at all, it doesn't make sense for there to be an alias
does this work bro
Yes
Are you familiar with python?
You should get familiar with python first
knowing js just the basics might be enough

What's wrong with discord.py?
Ironic joke lol between dpy heads
what's dpy
@commands.Cog.listener()
async def on_ready(self):
for color_role_id in config.colors:
color_role: discord.Role = self.bot.get_guild(config.main_server).get_role(color_role_id)
print(color_role)
print(color_role.members)
why is this not printing the role members? note: it does get the role successfully
can you invite me to it ive been looking for that server for a while
What intents are you requesting?
Also you probably don't want to do this in on_ready, that event fires repeatedly and randomly
im not trying to use any intents at all, i want to avoid intents as much as possible
this is just for testing purposes im gonna put it into a repeating loop later
You need specific intents for get_guild to work
no u dont, actually
wait
?
wait nvm, i thought of something else
I believe you need the members intent to see the members of a role
!e
code
print(isinstance(0, (str, int))
!e
code
!e
print(isinstance(0, (str, int))
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print(isinstance(0, (str, int))
003 | ^
004 | SyntaxError: '(' was never closed
!e
print(isinstance(0, (str, int)))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
!e
print(isinstance('0', (str, int)))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
!e
print(isinstance([0, 1], (str, int)))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
False
https://discord.com/channels/267624335836053506/267659945086812160 is the correct channel for this
oh my bad
Can you use the walrus operator to assign variables like:
if (invite_match := re.search(
r"(?:https?://)?(?:[a-zA-Z0-9-]+\.)?(discord(?:app)?\.com|discord\.gg)/(?:invite/)?([a-zA-Z0-9]+)$",
message.content, re.IGNORECASE)):
yes
Can you put py await client.process_commands(message) at the start of your function instead of the last line?
yeah
Often when people do that, what they want is a listener rather than overriding on_message
@fast osprey one dude
!e 2 +3 =
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | 2 +3 =
003 | ^^^^
004 | SyntaxError: cannot assign to expression
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
:white_check_mark: Your 3.12 eval job has completed with return code 0.
5
#bot-commands exists people
!e print'uwu'
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print'uwu'
003 | ^^^^^^^^^^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
!e print("uwu")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
uwu
!e print("code")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
code
https://discord.com/channels/267624335836053506/267659945086812160 exists if you want to run bot commands
how can I perform each task in turn (sequentially, one after the other). I am using aiosqlite and my database is being blocked due to multiple tasks
What database/driver are you using?
Task loops are meant to be for background repeating things, not things you execute once with dependencies
is there a way to get the connection link of user , meaning whatever they have connected with their profile can i check with bot?
these things in my case
no
: (
What is this color called?
or do you mean green
The green
green?
both are green
#43B483
I know but it's should be an official Discord color
these are the official discord colours
There is more colors than that
Why do you think that?
That is just whatever lib you are using
those are simply some presets of discord.Colour class
the embed color can be anything, not necessarily restrained to a preset
My guess is you have teal or dark teal
How can I ignore mute and deafen?
if (before.channel == after.channel and
before.self_mute == after.self_mute and
before.self_deaf == after.self_deaf):
return
This isn't really working
what condition are you really trying to check for here
Deafen/undeafen mute/unmute
But you said you want to ignore it?
What are you trying to detect changes in?
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
# Ignore changes if only mute or deafen status has changed
if before.channel == after.channel:
return
if before.channel is None and after.channel is not None:
action = "joined"
channel_name = after.channel.name
elif before.channel is not None and after.channel is None:
action = "left"
channel_name = before.channel.name
elif before.channel is not None and after.channel is not None and before.channel != after.channel:
action = "switched from"
channel_name = f"{before.channel.name} -> {after.channel.name}"
# Create embed
Join, leave and switch voice channels
You donβt need to βignoreβ anything, simply only look for the changes you want
Only issue i see is the last one might still run for other actions
I think before.channel != after.channel should be enough?
elif before.channel != after.channel:
action = "switched from"
channel_name = f"{before.channel.name} -> {after.channel.name}"
color = discord.Color.green()
Cannot find reference 'name' in 'None'
That's not in the code you sent
async def system_dependencies(self) -> None:
if not os.path.isfile('requirements.txt'):
async with aiofiles.open('requirements.txt', mode='w') as file:
await file.write('')
try:
async with aiofiles.open('requirements.txt', mode='r') as file:
dependencies = await file.readlines()
dependencies = [dep.strip() for dep in dependencies if dep.strip()]
missing = []
for dep in dependencies:
try:
pkg_resources.require(dep)
except pkg_resources.DistributionNotFound:
missing.append(dep)
except pkg_resources.VersionConflict:
missing.append(dep)
if missing:
process = await asyncio.create_subprocess_exec(
sys.executable, "-m", "pip", "install", *missing,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode == 0:
print(f"Dependencies installed successfully:\n{stdout.decode()}")
else:
print(f"Error during installation:\n{stderr.decode()}")
else:
print("All dependencies are already installed.")
except Exception:
traceback.print_exc()```
@fast osprey How could I improve it?
How do i mention a role in string?
assuming if you're on discord.py and you have a role object, role.mention would give you the appropriate mention format
if you just have the ID, <@&id> would be the format otherwise
https://discord.com/developers/docs/reference#message-formatting
thanks
pip install -r requirements.txt
how tf do u make theese boxes
Back ticks on both sides `
how do i check if a command instance is a slash command?
What does "command instance" mean here?
an instance of a command?
I mean it depends on ur use case
command isn't a thing as far as the library is concerned. There are multiple Command classes, of which you would need to disambiguate here. Some code would probably be useful as well as what you're trying to do
Is there a bot that does OCR?
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.
This is called when one or more of the following things change:
β’ status
β’ activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
Is it recommended to add a class inside another class (cog)?
for what reason?
That is what Rapptz did
Yeah, there are no nested classes?
...where do you see classes nested?
Am I using the cogs incorrectly?
Cannot find reference 'edit_message' in '() -> InteractionResponse'
The command is outside of the cog for one
and for that, that's just your ide complaining
C:\Users\luffy\Downloads\meowmeowmeow\cogs\music.py:65: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(Music(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog music.py: Extension 'cogs.music' raised an error: TypeError: object NoneType can't be used in 'await' expression```
can anyone help?
Still getting same error
raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.verification' raised an error: TypeError: object NoneType can't be used in 'await' expression
both setup and add_cog are async in dpy as of 2.0
Do you know what I'm supposed to do?
Yeah, make setup an async method and await add_cog. And more generally, follow official docs and examples
I'm using await self.load_extension("cogs.verification")
I didn't mention load_extension though 
Should I make this to all my cogs?
Is there any downsize of using async?
I mean, add_cog is a coroutine. You need to await it.
The library also assumes when it calls setup that it is supposed to be async and awaits it, so it should be async.
Do you know why the ide is complaining?
Because of some silly thing with how it fails to read that particular method from the library, it's a pretty common thing
Do you know why the existing button is not syncing on_ready in the cog? https://paste.pythondiscord.com/5PJA
making a method called on_ready in a cog doesn't do anything
You also probably don't want to actually use on_ready anyways, given how it actually works
Do you have any idea on how I can sync the old button?
What does "syncing" a button mean?
Like make a button work after a restart?
Exactly
C:\Users\luffy\Downloads\meowmeowmeow\cogs\music.py:65: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(Music(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog music.py: Extension 'cogs.music' raised an error: TypeError: object NoneType can't be used in 'await' expression```
can anyone help?
async def setup(bot):
await bot.add_cog(VerificationCog(bot))
You need to async it
(the cog)
Look at the persistent.py example in the repo
You don't need to edit a message, you just need to register either a persistent view or a dynamic item. And you should do this once, not in on_ready
thank you it worked but i want to make my bot status to have a mobile status but im using python and discord.py
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers')) this is only working for 1 server
Also this is running everythime i run the bot @bot.event async def on_guild_remove(guild): channel = bot.get_channel(channel_id) await channel.send(f"server leave server:{(guild.name)} owner: {(guild.owner)}") await botlist_client.setStats(len(bot.guilds), 1) await bot.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers'))
it sends this:
server leave server: `````` owner: None
If you don't have members intents, it's gonna be None, it needs members cache to get the member obj
no it just happens as soon as i start the bot
anyone here worked with lavalink?
u gave too little info, guild.owner is returning none, cause of that can be several things
as soon as i start the bot its sends that
not because someone kicked my bot
Intents = discord.Intents.all()
client = commands.Bot(command_prefix='.', intents=Intents)
u have these?
and do u have channel_id defined
yes
channel_id is defined
its sending it in the channel
but also
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers')) why is this only showing in one server
@bot.event
async def on_ready():
print("bot online")
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{len(bot.guilds):,} servers'))
bot.add_view(VerifyButton())
upload_json_to_discord.start()
await botlist_client.setStats(len(bot.guilds), 1)
print(f"{len(bot.guilds):,} servers")```
You shouldn't be doing any of this in on_ready
why?
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

