- discord enforce slash when they made message content a privileged intents -> no content no command
- you cannot apply for message content w/ the reason of message command
- slash command has a different framework than dpy's text commands (slash is too limited)
- hybrid command exist now, making slash/text compatible, but text is limited by slash
#discord-bots
1 messages · Page 185 of 1
Is this the right way to do it?
@client.command(name = 'queue')
async def queue_command(ctx):
# Check if the message was sent in the allowed channel
if ctx.channel.id == 712074759453671494:
# Check if the user is in the specified voice channel
if ctx.author.voice is None or ctx.author.voice.channel.id != 712072729406472374:
if ctx.author not in queue: # Check if the user is not in the queue
queue.append(ctx.author)
await ctx.send(f'{ctx.author.mention} has been added to the queue.')
else: # The user is already in the queue
await ctx.send(f'{ctx.author.mention} is already in the queue.')
else: # The user is in the specified voice channel
await ctx.send(f'{ctx.author.mention} is already in the voice channel and cannot be added to the queue.')
else: # The message was not sent in the allowed channel
await ctx.send("This command can only be used in the [#712074759453671494](/guild/267624335836053506/channel/712074759453671494/) channel.")```
I'm not sure if I should use if ctx.author.voice is None or ctx.author.voice.channel.id != 712072729406472374: or something else?
You should use guard clauses instead of nesting if statements: ```py
async def queue_comnand(ctx):
if ctx.channel.id != ...:
await ctx.send(...)
return
elif ...:
await ctx.send(...)
return
...
queue.append(ctx.author)
That looks fine tbh
So you mean like this right,
@client.command(name = 'queue')
async def queue_command(ctx):
if ctx.channel.id != 712074759453671494:
await ctx.send("This command can only be used in the [#712074759453671494](/guild/267624335836053506/channel/712074759453671494/) channel.")
return
if ctx.author.voice and ctx.author.voice.channel.id == 712072729406472374:
await ctx.send(f'{ctx.author.mention} is already in the voice channel and cannot be added to the queue.')
return
if ctx.author in queue:
await ctx.send(f'{ctx.author.mention} is already in the queue.')
return
queue.append(ctx.author)
await ctx.send(f'{ctx.author.mention} has been added to the queue.')```
Yes
Is it better to convert duration seconds to minutes before inserting it into the database for a mute infraction, or to keep it in seconds and convert it for display purposes only?
seeing this error
don't see the error 
convert it only for display purposes, and you should rather use the discord timestamp formatting, you won't have to convert it that way
bhru
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
You mean with discord.utils.snowflake_time?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
you can convert your seconds to a timestamp easily
How can I make it appear in minutes? Example, Duration: 30 minutes
no but you can look into the styles they provide
you can use the relative time format
style = r
I think that's what you're looking for
Duration: 5 years ago doesn't make any sense
It should display the actual duration for the infraction
have you converted the seconds to a datetime object?
It shouldn't be used as a timestamp
or a timedelta
hm
well, then just convert the seconds to minutes and stuff yourself
Is it a good way to insert the duration seconds as an integer?
Or should I keep it as a string?
shouldn't you be taking in another argument after ctx?
Just get command you wanted to run as an argument
Way way way cleaner
And why are you even converting IDs to string to compare them
Sure
Don't want anything I see
ive no clue honestly
If your bot can't access message contents, it can't process commands
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
Getting this error when using dynamic cooldown
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 700, in _run_event
await coro(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1361, in on_application_command
await self.process_application_commands(interaction)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1353, in process_application_commands
await app_command.invoke(interaction)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/slash_core.py", line 719, in invoke
await self.prepare(inter)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 331, in prepare
self._prepare_cooldowns(inter)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 315, in _prepare_cooldowns
bucket = self._buckets.get_bucket(inter, current) # type: ignore
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 227, in get_bucket
self._verify_cache_integrity(current)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 212, in _verify_cache_integrity
dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 212, in <listcomp>
dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
AttributeError: 'function' object has no attribute '_last'
My code:
def drop_cool(msg):
if msg.author.id == 756018524413100114:
return None
print(msg.author.id)
return commands.cooldown(1, 600)
@commands.slash_command(description="Drops card")
@commands.dynamic_cooldown(drop_cool, commands.BucketType.user)
async def drop(self, inter: discord.ApplicationCommandInteraction):
...
commands.cooldown is a decorator
the dynamic_cooldown callable is supposed to return Optional[Cooldown]
im guessing you just forgot to capitalize the C
Hi, my discord bot doesnt show its slash commands anymore, it worked until now but now none of them works
like this async def askgpt(ctx, arg):
did you setup the intents in your code?
intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)
``` for example
are you using a python framework like discord.py?
yes dsicord pip module
Oh, thank you for the info !
what error are you getting?
Basic slash command examples with discord.py are available here: https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
can you double check the discord.py version you have installed with pip list?
the gist 😔
did you run pip install --upgrade discord.py?
are you definitely sure you had the --upgrade flag? i cant think of a reason why it wouldnt upgrade otherwise
besides pip referring to another virtual environment
i mean a python virtual environment, not the remote console you're using
what command are you using to run your bot on the server?
wait so if you run pip list --outdated it really wont show discord.py as needing an update?
discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
how to open that?
"opening" an error message?
error message this
ah screw it does it work if you run pip install discord.py==2.1.0
discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
but what is "opening" an error message? do you mean how to fix the error message? or hide it?
fix
I just make a bot which user have premium it will work on dm or anywhere
@commands.has_any_role(role)
but not working it gived this eror
NoPrivateMessage is raised by the @commands.guild_only() check (and other guild-related checks, i forgot those raise it too), so if you dont want to see it you should either remove the check, or make an on_command_error listener that doesnt print that message
How would has any role work in DMs 🤔
i want only people with premium role to run this command but in dm
what scope should i choose for this bot for oauth2
if I use only works in dm everyone can use it
write a custom check then, if they're in a guild DMs then verify their premium status, otherwise check their role
But this command works in diffrent server with same code , I can run it in dm in difrent srver
if i use client.tree.comand and guild what scopes should i use for oauth2
what? DMs arent associated with any server so that doesnt make sense
Liek how idk.
you just need the application.commands scope to register commands, though ive never tried making a bot without the bot scope either
ok
@commands.has_any_role() will "work" in any guild, just not in DMs, hence why i pointed to a custom check
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
just use virtual environments, fixes most permissions and version related issues
!venv
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
is discord api down or something?
Just checked
https://discordstatus.com/incidents/dr5kywl9dwg9
ah, your python version is too old
2.0 raised the required version to 3.8 as described in that message
uhh i mean discord.py 2.0 raised the required python version to 3.8
only the slash menu
there's stable versions upto 3.11 available now... consider upgrading to 10 or 11 since you are upgrading
what operating system do you use?
oh i think the apt repo is updated with 3.10
if you're currently using the system-provided python, i would suggest installing pyenv or similar and have it compile 3.11 for you, that way you arent potentially breaking your system
Python package can't be upgraded, cause different python versions are different packages
You can install new with sudo apt install python3.11 then you would have to do some path stuff and there you go
If you only run the bot on that server you should just use docker
I don't see a problem using docker for small applications
how can i make very simple discord bot with slash command for for example /say text:hi and output is hi but its only example
How can I make a user specific command?
so like in the same way that I can do @commands.has_role("Admin"), how can I do that but for a user ID (so that only my id can run the command)
I believe there's an is owner check
Except it's not necessarily my server
(a bot that i have in 2-3 servers that i own) so that i can use on my alt too
Worth a shot lol
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
But I know it does exist
Ty
.checks is only used for app_commands
is there a way to make it user id specific?
so to specify 2-3 id's?
🛐 right back at you
Your ID is the same in all servers
if ctx.member == id
ik but i and 1 other account only i want to be able to run the command
alr
Add it to the team
yeah thats what i had in mind ty
check the pins
using an iterable isn't even a next level logic lmao
ok then how's that basic
@frail notch you can also specify owner_ids in your bot instance it takes a list so owner_ids=[123, 456, etc]
if you used iterables, that would require an if statement too
oh, how do you think I could get around that?
When you sudo apt remove --purge --autoremove -y python on linux
Btw discord disabled slash commands
Funny how I got a bunch of ratelimit errors when they did it
cant relate i just syuuuuuu my system
What could I use to match different time units?
def convert(time):
pos = ['s', 'm', 'h', 'd']
time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600*24}
for p in pos:
if p in time:
num = int(''.join([i for i in time if i.isdigit()]))
return time_dict[p] * num
return None```
I went to sleep but will try now, my guess is no it won’t.
question... what format is the assets parameter? I know it says similar to Activity, but that's rich presence.
what works in this field?
do i need to use something like assets=discord.Activity.assets("image_name", "image_url")?
Can somebody please tell me if this is the correct way to do it?
duration_seconds = for database
duration_string = for embed
Let me know what have happened
hi, I created a slash command that makes a poll with reactions
...
msg = await interaction.response.send_message(embed=embed)
for i in range(nb):
await msg.add_reaction(options[i])
...
Is it normal that the bot doesn't add any reaction?
I'm new to slash commands
Does it send the embed?
yes, it does
Where is nb defined?
nb is the number of responses I submit , nb = len(reponses)
and options is a list containing the emotes from 1️⃣ to 🔟
I just want to know if it's linked to the response.send_message
or if the code I sent should work
Can you show the entire function?
didnt work
can anyone help with this still?
How would I add a URL button on this command?```py
@bot.command()
def verify(ctx):
embed=discord.Embed(
title="Verify",
description=f"Verify with core bot`",
color=0x36393F)
await ctx.send(embed=embed, BUTTON TO URL)
assuming you're using discord.py 2.0 or a fork of that version (like disnake), you'd construct a discord.ui.View instance which will contain the message components, then add your URL button to it and send a message with that view: ```py
view = discord.ui.View()
button = discord.ui.Button(label="Google", url="https://www.google.com/")
view.add_item(button)
await ctx.send(..., view=view)``` (URL buttons are a unique case where the above syntax is acceptable, other kinds of buttons would be better suited for the subclass/decorator syntax)
other examples are in their repository:
https://github.com/Rapptz/discord.py/tree/master/examples/views
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
thanks
@sick birch What is a good way to check if any mutes have expired. If a mute has expired, the bot should unmute the user?
What mechanism are you using to mute? The old way or discord's new timeout feature?
Well for the new timeout feature you don't really need the bot to unmute you, right.
Hm, fair enough
I'm currently using the timeout feature. But the problem is you cannot mute people for longer then 1 week.
Generally people just do
# apply mute to user
await asyncio.sleep(time)
# remove mute
But I can see problems with that approach for long mutes
Yes exactly. What if the bot restarts
What about background task that runs periodically and checks if any mutes have expired?
Nah
That has potential to keep a user timed out longer than they should
The more robust solution would be to store expiration in a database
And on startup load the expiriation - current_time, an asyncio.sleep() that duration
await ctx.send(":001callisto: **WARNING: This will remove the user entirely from the system, would you like to proceed?** :001callisto:")
msg1 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
if msg1.content == "y":
await ctx.send("What is the reason for removing?")
msg2 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
await member.remove_roles(defined_roles)
await member.edit(nick=None)
dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
remove=discord.Embed(
title=f"User Removed - {member.tag} ✦",
timestamp=datetime.datetime.utcnow(),
color=discord.Color(0xac0101)
)
remove.add_field(
name="User ID:",
value=f"``{member.id}``"
)
remove.add_field(
name="Reason:",
value=msg2.content,
inline=False
)
remove.set_footer(text=f'{member.id}')
await ctx.send(embed=remove)```
recognises the content of the first message (y) and responds correctly but for msg2 it doesn't respond with anything, does anyone know why?
And it just hangs here?
Mm. on_ready not being triggered?
Hm. Do you have any error handling set up?
No, don't
I ask because usually people don't write error handlers properly
And it doesn't show anything in console
Then I'm left troubleshooting for 20 minutes before I realize they have a shoddily written error handler
But uh, could just be a temporary discord issue. They've been having a quite a few of those lately
Something seems to be off
it was resolved
you might have something blocking in the setup hook if nothing after logging with static token gets executed
Could be as setup_hook is one of the first things to be called
Can we see your setup hook?
You probably don't have one if you have client = commands.Bot
Skill issue🐟
Usually people use it with a subclass
I'm not seeing a setup hook
Same exact code?
If you're on VCS make sure they're on the same branch and have latest commits
What are your curling?
See if ping 8.8.8.8 goes through
Ah ping goes through fine
ping discord.com?
I can't tell if that's a successful ping or not
personally i use a combination of a loop and sleeping tasks for my reminder system
- on bot startup / every 10 minutes, schedule every reminder due within the next 11 minutes
- on reminder add, store in database and if close to due, schedule a task
- each task sleeps until due date, and then sends the reminder
Something is off with your server then
Is it a self hosted server or is it cloud?
i would check with customer support then
"little vps" generally have this sort of issue
I'm gonna shill AWS then
I use it for my sites, bots, domains, emails + works great
but hetzner is great as well
average cloud provider experience
understandable
Solution: don’t use a VPS and surrender all of your Brain cells
Is this a good solution to handle durations accurately?
elif duration_seconds < 86400:
hours = duration_seconds // 3600
if hours == 1:
return "1 hour"
else:
return f"{hours} hours"
else:
days = duration_seconds // 86400
if days == 1:
return "1 day"
elif days < 7:
return f"{days} days"
else:
weeks = days // 7
remaining_days = days % 7
if remaining_days == 0:
return f"{weeks} weeks"
else:
return f"{weeks} weeks and {remaining_days} days"```
I don't want 15 days to be displayed as 2 weeks etc
Hey, could anyone help me use discord slash in my code? I haven’t coded in a while, and can’t find how to import it into my code, or what module to use.
Alright ty
@sick birch Damn is there an easier way to accomplish this task? https://paste.pythondiscord.com/lutejuzocu
😢
!e
seconds = 734856
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
print(f"""Seconds: {seconds}
Minutes: {minutes}
Hours: {hours}
Days: {days}
Weeks: {weeks}""")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Seconds: 36
002 | Minutes: 7
003 | Hours: 12
004 | Days: 1
005 | Weeks: 1

I want to display the duration of a specific time period grammatically correct. Specifically, when the duration is one week or two weeks and one day, the bot should not display "days" in plural form
@naive briar Did you check the code?
I did, and I don't know what it even does in the way it's written
It's converting seconds into the format
!e
def add_s(n: int) -> str:
return 's' if n > 1 else ''
seconds = 734856
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
print(f"""Second{add_s(seconds)}: {seconds}
Minute{add_s(minutes)}: {minutes}
Hour{add_s(hours)}: {hours}
Day{add_s(days)}: {days}
Week{add_s(weeks)}: {weeks}""")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Seconds: 36
002 | Minutes: 7
003 | Hours: 12
004 | Day: 1
005 | Week: 1
^
though i would probably suggest rewording it to "Ban Ends" so it be grammatically correct at least half the time
Because it should be displayed as the duration for the mute
timedelta parsing is always a royal pain in the arse
help still needed 😭
This will only return the largest unit of time
do you have any on_command_error handler? and what is defined_roles?
if defined_roles is a list, as i can only guess by the variable name, you should be getting an AttributeError: 'list' object has no attribute 'id' error because Member.remove_roles() doesnt take a list, but not seeing an error would also suggest you have an on_command_error that's suppressing the error message
of course, i could also be wrong if defined_roles is just a Role object, but that's omitted from your code
also worth pointing out that you have two inconsistent references of datetime.now() and datetime.datetime.utcnow() - only one of these will work depending on how you imported the datetime module
Defined roles is just an object
I didn’t see that, thank you
I don’t have any errors
and do you have any on_command_error handler (or its other related forms)? because you should have at least gotten an error for the datetime being wrong
@naive briar Is this better? https://paste.pythondiscord.com/fotazewado
how'd u do this?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Looks good to me 🤷. The else is redundant though, and I'd suggest using a list and joining it at the end instead of concatenating to a string
never understood why people used the useless else in some code, but eh
Can you inherit from commands.HybridGroup in the same way you can inherit from commands.GroupCog?
Idk either
are we allowed to self promote or invite people to test our bots on a separate channel? (looking for guinea pigs for a GPT DC Chatbot)
1st : no
2nd: that depends on the user
Sure, though I don't think dpy supports the use of custom subclasses for hybrid groups. You'll have to add the group "manually"
oh dang, also can u use slash command defualt perms on sub commands?
Subcommands inherit all of the default perms of its parent (you can't have specific perms for specific subcommands)
If anyone would like to join my server for some testing I would appreciate it.
I just want to see that server permissions and stuff work right.
the GPT model is text-davinci-003 with midjorney in there too.
!rules 6
@fading marlin thanks
You're welcome?
Again if anyone would like to help let me know !
yes, I have an on_command_error for missing arguments and missing roles
type object 'member' has no attribute 'tag'
File "/Users/myname/Custom bot/main.py", line 194, in remove
title=f"⠀⠀ User Removed - {discord.Member.tag} ✦",
^^^^^^^^^^^^^^^^^^
File "/Users/myname/Custom bot/main.py", line 222, in <module>
spooky.run(bot_token)
AttributeError: type object 'member' has no attribute 'tag'
@hushed galleon
You need an instance, not the class
and tag doesn't even exist
it's discriminator, don't guess random fields
discord.py has a good api reference
https://discordpy.readthedocs.io/en/latest/api.html#member
thank you
np, look at what lee said though, discord.Member refers to the class, it can't tell what member you are talking about
will do!
Hello can someone help me with something i want to display a set of 10 items and i want to have 2 emojis on the embed right and left arrow when you hit the right arrow you go to a new set of links and when you hit the left arrow you go back to the other links
Hi all, i have one question
how to run function from module
the function
@bot.command(name='hi')
async def SendMessagehi(ctx):
await ctx.send('Hello')
how call from another programm module to send Hello to discord chat?
Thanks
fyi you can make actual code blocks like this:
```lang
code
```
just makes the code more readable
hmm) looking in google 5 min ago for this silution, how python block code makes?
what even is this
use Context.invoke
@slate swan
will try, ok, thanks:)
any way to check if sparkles is in the embd
i have the whole code just need help with regex
!d discord.Embed.description
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
if "✨" in embed.description: ...
You can also check against the emojis unicode directly iirc: \U00002728
right, that's a better way
its's basically the same thing ( usually)
if you use "\u2728" it will output the sparkles emoji
!e print ("\u2728")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
✨
I'm making a custom embed parser, and \n isn't actually making a new line and instead just having \n in the code?
.replace("\\n", "\n")
Trying to send an image to discord without saving it (Using Pillow)
font = ImageFont.truetype("font.ttf", 28, encoding="unic") # Define Font
bg = Image.new('RGB', (x, y), "black") # Creates the image
at = ImageDraw.Draw(bg)
at.text((5, 5), text, (255, 255, 255), font=font) # Adds the text
bg.show()
f = bg.to_file() # <- Error
await interaction.response.send_message(file=f)
This is what I have, but I'm getting an error.
File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "directory\bot.py", line 622, in textimage
f = bg.to_file()
File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\PIL\Image.py", line 517, in __getattr__
raise AttributeError(name)
AttributeError: to_file
The above exception was the direct cause of the following exception:
File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test_image_text' raised an exception: AttributeError: to_file
Ideas?
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
!d PIL.Image.Image.save
Image.save(fp, format=None, **params)```
Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the [image format documentation](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html) for each writer.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the `seek`, `tell`, and `write` methods, and be opened in binary mode.
image = your pillow image
image.save(buffer_io:=io.BytesIO(), "PNG")
file = discord.File(buffer_io, "filename.png")
^
Thanks again, Vanessa!
So I’m trying to reduce the length of my code. To do so I’m trying to implement aliases. A couple of them work but I cannot for the life of me figure out why on some they keep saying there is no command by “apex” anyone have any idea?
I thought maybe spaces were the issue, but other ones with spaces work fine
Yeah you can't have spaces in command names
Not sure why the other ones work, they shouldn't
Aliases are the same way?
Yes
Alright, tyvm
Not working...
I've probably just done something wrong.
channel = interaction.channel
font = ImageFont.truetype("font.ttf", 28, encoding="unic")
bg = Image.new('RGB', (x, y), "black")
addtext = ImageDraw.Draw(bg)
addtext.text((5, 5), text, (255, 255, 255), font=font)
bg.show()
bg.save(buffer_io:=io.BytesIO(), "PNG")
f = discord.File(buffer_io, "testimagetext.png")
await channel.send(file=f)
Sends a blank, 0 Byte file.
Isn't it necessary to .seek(0)
Yeah do buffer_io.seek(0)
After you save to it
Just that?
Yes
We have success!
Thanks again Vanessa, thanks Exenifix!
Still thinking why is sarth vanessa now
dunno, i've been using bytesio and Image.save without seeking all this time in hikari
right, hikari handles it internally
😳 i have my reasons
@slate swan
yes?
nothing
have any other ideas how to run nextcord bot def in other way, not invoke becouse this is not external sourse, this is one multi module program?
what's wrong with context.invoke
i dont need to collect new task, just run one of nextcord bot def
like
@bot.command(name='year')
async def SendMessage(ctx):
await ctx.send(year)
form discord yeat return to you the year, so
i need to call this from another module of program, and get the year in discord chat
What is collect new task
invoke is task collector 🙂
Huh 
invoke just calls a command with given arguments though..?
Weird
i mean, either use Bot.invoke (or Context.invoke) or move the function of the command into a function and import it to wherever else you need to use it
Is this undocumented or am I insane 
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
invoke just calls a command with given arguments though
yes, i am not found this on examplaes...
discord/ext/commands/core.py lines 1014 to 1023
async def invoke(self, ctx: Context[BotT], /) -> None:
await self.prepare(ctx)
# terminate the invoked_subcommand chain.
# since we're in a regular command (and not a group) then
# the invoked subcommand is None.
ctx.invoked_subcommand = None
ctx.subcommand_passed = None
injected = hooked_wrapped_callback(self, ctx, self.callback) # type: ignore
await injected(*ctx.args, **ctx.kwargs) # type: ignore```
Hooked wrapped callback
thanks to all
does anyone have a list of good open source discords bots to reference?
want to get a good base to start off on
is that like a portfolio of discords bot?
@unkempt canyon :https://github.com/python-discord/bot
R.danny ( made by discord.py's developer ): https://github.com/Rapptz/RoboDanny
these are beginner friendly ( mostly )
thanks checking them out now 🙂
it's not something required, but people do make websites and wikis for their bots ( or guides for bot users)
only important thing you'll need for bot verification would be a ToS and privacy policy
oops i misread your question
yeah not at that stage yet lol
What do I do to get the bot name
property user```
Represents the connected client. `None` if not logged in.
Idk just check my github
Anyway to make a button only clickable by a certain role with @discord.ui.button
I mostly have bots in organisations
help what do i do?
Read the error
i followed this tutorial
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
In this tutorial, we'll use Replit and Python to build a Discord chatbot. If you're reading this tutorial, you probably have at least heard of Discord and likely have an existing account. If not, Discord is a VoIP and chat application that is designed to replace Skype for gamers. The bot we create in this tutorial will be able to join a Discord ...
Outdated
ah
how can I make a discord bot add a reaction each time a message is sent in a specific channel
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
Check the channel ID or whatever
why would you want to make it
good question, I'm programming a system and part of it requires a user to react to the message sent on command in the defined channel, so each time a message is sent the bot should automatically add a reaction there
Wouldn't it be smarter to just add a reaction whenever a command is used at this point.
Lemme guess
/test
Bot: Hey, how are you?
User: I am good! Bot reacts with
emoji
Bot: Noice, gtg bye cya!
Ig
no
but good guess
I guess yes, but the channel is specifically for the bot anyway
what's the point of it
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@slate swan
yo sup
Will ask later, have coaching rn 
kkk
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
You can separate all other actions by comparing bot adding action with entry.action
hi, why i have a infinite loop?
@commands.Cog.listener()
async def on_message(self, message, *, member_mention:discord.Member=None):
user= message.author.mention
if message.author==bot:
return
if member_mention == None:
if message.content.startswith("bonjour"):
await message.channel.send(f"Bonjour {user}")
else:
await message.channel.send(f"Bonjour {member_mention}")
if message.content.startswith("Bonjour"):
await message.channel.send(f"Salut {user}")
else:
await message.channel.send(f"Salut {member_mention}")
if message.content.startswith("Bonsoir"):
await message.channel.send(f"Bonsoir {user}")
else:
await message.channel.send(f"Bonsoir {member_mention}")
if message.content.startswith("bonsoir"):
await message.channel.send(f"Bonsoir {user}")
else:
await message.channel.send(f"Bonsoir {member_mention}")
thanks
infinite loop again...
on_message doesn't have member_mention:discord.Member=None parameter
it only takes message
if you want to get the mentions in the message you can use message.mentions
although not sure why it is looping. Can you share your code?
What is bot variable
It seems like you're in a cog
It should be like self.bot or something
bot is an commands.Bot instance

you're looking for the ClientUser instance to compare with the author
!d discord.Client.user
property user```
Represents the connected client. `None` if not logged in.
None if not logged in 
I'm going to school, maybe in 30 minutes?
Printing Client.user before running it would return None
yes I am looking to do this because I feel like my bot is responding to itself. so I would like to find the solution so that this is not the case and that it stops responding to itself, I have searched no matter how I can't find the solution and since I am still limited in the code sometimes I don't really understand what I'm doing so if someone could possibly guide me that would be really nice
I have a hard time with the discord documentation. py, I don't understand anything about it
you're right, they probably defined the bot variable as a new commands.Bot instance or something to get rid of the NameError instead of using the correct instance
@vocal snow as soon as i get home i'll paste the code for you
How about refactoring
content = message.content.lower()
if any(content.startswith(word) for word in ("bonjour", "salut")): # etc
await message.reply(f"{message.content.split(maxsplit=1)[0].title()} {message.user.mention}")```
Code must be dry!
Wow wow wow...
well you need to check if the message author is the bot itself .. that'd be bot.user == message.author, bot being your commands.Bot and message being the discord.Message instance
also, as others said you don't need to define bot again in a cog
adding a ```py
if message.content is None: return
Can it even be None?
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
Unicode char 💀
Empty string
It can be None anyway
Hi, I needed help with top.gg api, if anyone here has some experience with that.
top.gg uses webhooks, so I created a POST route on my flask app
I just wanted to know how to authorize it.
🚶♂️ ig i should start reading dpy docs again
yeah it can't be None
confused with hikari for 3rd time in day ™️
use the authorization header while making the web request
topgg/http.py lines 105 to 109
headers = {
"User-Agent": self.user_agent,
"Content-Type": "application/json",
"Authorization": self.token,
}```
the second and third one are needed in your case
oh thanks
I'm getting none with request.headers.get("Authorization")
@slate swan ^
you don't get it, you need to set it
await post("/endpoint", headers={"Authorization": "your client token","Content-Type": "application/json"})
Authorise you mean set webhook secret and just compare it?
@vocal snow my code:
https://pastebin.com/6gGcheAs
on_message can't have a member_mention kwarg
only message kwarg
arg
how i can run this code corretly?
take out the member_mention kwarg
member_mention:discord.Member=None?
yes
if that is what identifies as member_mention in the code
ok, but in this case, how can I create my condition?
which condition
because I'm unable to open pastebin again for some reason
why does pastebin suck so much
still unable to open 
before, i has this code:
@commands.Cog.listener()
async def on_message(self, message):
if message.content.startswith("bonjour"):
await message.channel.send(f"Salut {message.author.mention}")
if message.content.startswith("bonsoir"):
await message.channel.send(f"Salut {message.author.mention}")
if message.content.startswith("Bonjour"):
await message.channel.send(f"Salut {message.author.mention}")
if message.content.startswith("Bonsoir"):
await message.channel.send(f"Salut {message.author.mention}")
so how is this relating to member_mention
but I want to add my condition that if I mention a member, the message must be different
you can access the mentions using message.mentions
it will return a list of User objects
at the end of code?
in the on_message 💀
sorry 😕
do you think you have enough python knowledge to create a discord bot? just asking

I'm new to python, I have some basics, but discord.py is causing me a lot of trouble indeed. I'm having a hard time understanding the documentation for discord.py
I know how to write some basic commands, make embeds, but from there to create a complex bot, I am not capable of it
hm, that's fine then, goodluck
do you know how to use python classes? That's generally the reason for not understanding the docs
If understood correctly, Classes are like a directory containing several commands?
I don't know if it's said like that in English...
you're not completely wrong, but there's a lot more about them you should know
https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc you can learn about them here
I should try to understand better with tutorials in French.
It doesn't work like that?
did you set up a authorization here or not?
I did.
That's the problem, I did set up here but it is still returning None
can we see more of your code?
@app.route("/topsecrect/getvotes", methods=["POST"])
def votes():
a = request.headers.get("Authorization")
if a=="youshallnotpass":
print("Yes")
else:
abort(401)
oh, where does the request variable come from?
from flask import request
buser = await bot.fetch_user(user.id)
b_embed = discord.Embed(color=c.random(), title=f'{user.name}\'s Banner')
b_embed.set_image(url=f'{buser.bannner}')```
`AttributeError: 'User' object has no attribute 'bannner'`
i'm not very experienced with flask ( i use fastapi for these purpose ), but are you sure it's meant to be used that way?
bannner
oops ty
It is.
hm it seems like flask works that way
can you try printing the headers and see if your token is part of some other header here
I've got my whole site in that app
I've tried
yep, i just wasnt aware
It returns everything other than authorization
weird part is when I send a custom request from another script, it does get the headers
interesting, lemme try it
is there a way to change the style of the button after it has been clicked
<button obj>.color = ButtonStyle.<you choice>, then edit the message with view object
okay!
It does. You set the secret on topgg settings then they send it to you on every request they make to your webhook
Attempting a server info command, received this error upon execution:
discord.app_commands.errors.CommandInvokeError: Command 'serverinfo' raised an exception: AttributeError: 'Guild' object has no attribute 'region'
@bot.tree.command(name = "serverinfo", description = "Provides information on the server")
async def serverinfo(interaction: discord.Interaction):
guild = interaction.guild
embed = discord.Embed(title = f"{guild.name} Info", description = "Information of this Server", color = 0xf6ff00)
embed.add_field(name = "Server ID", value = f"{guild.id}", inline = True)
embed.add_field(name = "Created On", value = guild.created_at.strftime("%b %d %Y"), inline = True)
embed.add_field(name = "Owner", value = f"{guild.owner}", inline = True)
embed.add_field(name = "Members", value = f'{guild.member_count} Members', inline = True)
embed.add_field(name = "Channels", value = f'{guild.text_channels} Text | {guild.voice_channels} Voice', inline = True)
embed.add_field(name = "Region", value = f'{guild.region}', inline = True)
embed.set_thumbnail(url = guild.icon.url)
embed.set_author(name = f'{interaction.author.name}', icon_url = {interaction.message.author.avatar.url})
await interaction.response.send_message(embed=embed)```
Any help would be great <3
That's what I've been doing.
Then why do you say "it doesn't work like that"
I was asking whether it works like that or not
It was a question
English is weird then
I did add a question mark lol
import flask, random
from flask import request
app = flask.Flask(__name__)
@app.route("/")
def home():
return "yo"
@app.route('/vote', methods=["POST"])
def vote_add():
assert request.headers.get("Authorization") == "#mypassword"
print("works")
# running the app
``` output: ```sh
* Serving Flask app 'main'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:4686
Press CTRL+C to quit
172.31.128.1 - - [25/Jan/2023 13:55:54] "GET / HTTP/1.1" 200 -
works
works for me
i did a test vote from the "send test" option
Attempted to remove the region and embed.set_author lines to see if it would work without since both caused issues, and now I get the error In data.embeds.0.fields.4.value: Must be 1024 or fewer in length.
i have discord.py installed by the module is not detected
Requirement already satisfied: aiohttp<4,>=3.7.4 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from discord.py) (3.8.3)
Requirement already satisfied: attrs>=17.3.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (22.2.0)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (2.1.1)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (6.0.4)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.8.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.3.1)
Requirement already satisfied: idna>=2.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<4,>=3.7.4->discord.py) (3.4)
PS C:\Users\Gabriel\Desktop\projetos python> & "c:/Users/Gabriel/Desktop/projetos python/venv/bin/python.exe" "c:/Users/Gabriel/Desktop/projetos python/RP Utilities/rp_main.py"
Traceback (most recent call last):
File "c:/Users/Gabriel/Desktop/projetos python/RP Utilities/rp_main.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'```
You have to install discord.py in the venv
how to display the username of the user including their name and discriminator
If it throws up an error just do Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned on powershell with admin perm
Did I mess up the total text channel/total voice channel commands
I think that's why it gives me that error
the members and channels fields can be way too long ... you might want to slice them off
yes
the max chars you can have is 1024
So how do i change it to just display the total amount of text/voice channels
embed.add_field(name = "Channels", value = f'{guild.text_channels} Text | {guild.voice_channels} Voice', inline = True)```
!d len
len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
guild.text_channels is a list ( same for .voice_channels), using len gives you the number of items in it
Ah I see, thanks
I also get the error discord.app_commands.errors.CommandInvokeError: Command 'serverinfo' raised an exception: AttributeError: 'Guild' object has no attribute 'region' when this line is added:
embed.add_field(name = "Region", value = f'{guild.region}', inline = True)```
Is {guild.region} incorrect?
They removed it
Oh they did?
To my knowledge, anyways
okay, i tried to execute this and this happened
translation: the system cannot find the specified path
!venv
notice the . before environment name
oh actually that's not it
can you do ls
Is it possible to find the amount of boosts a server has or nah? Cuz I searched "boost" on the discord.py api and I got nothing
i'm at windows
or better, usin' windows
Nevermind, it's premium_subscription_count, not boost
oh, but do you have a folder named env created in your environment?
if yes, try the other env script variants ( ps1 and the other one ) instead of bat
i suggest running dir env\Scripts to check, but i cant think of a reason why virtualenv wouldn't generate the corresponding batch file for activation...
btw this should go in a help post on #1035199133436354600
yes, and how do i do it?
!venv the alternative commands are listed here .venv will get replaced by your environment name
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
!treecommands
!add_command
im tryna to add options to tree commands anyone help?
Pins
example?
In THE PIN
thanks
so i got @bot.tree.command
and @strange knoll_commands idk what to add to make it a option
make what an option
just make a parameter on the command callback
ok
thanksd
what do you think it's the best way to retrieve #, User, Messages, Exp, Level from a MEE6 leaderboard?
url = "https://mee6.xyz/en/leaderboard/779531957222375455"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
# Find the div containing the leaderboard data
div = soup.find("div", class_="leaderboard-list")
print(div)
# Create an empty list to store the data
data = []
# Extract the data
for i in div.find_all("div", class_="leaderboard-list-item"):
rank = i.find("div", class_="leaderboard-list-item-rank").text
user = i.find("div", class_="leaderboard-list-item-username").text
messages = i.find("div", class_="leaderboard-list-item-messages").text
exp = i.find("div", class_="leaderboard-list-item-exp").text
level = i.find("div", class_="leaderboard-list-item-level").text
data.append([rank, user, messages, exp, level])
# Create a csv file and write the data to it
with open("leaderboard.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["#", "User", "Messages", "Exp", "Level"])
writer.writerows(data)
print("Data saved to leaderboard.csv")
I was thinking about something like this, but the div found it always empty
What is the audit log event for discord bot add
You need to get it manually like you can use on_member_join to detect it or use on_integration_create since bot creates integration altho i dont recommend this
!d discord.AuditLogAction.integration_create
A guild integration was created.
When this is the action, the type of target is a PartialIntegration or Object with the integration ID of the integration which was created.
New in version 1.3.
you can check if the member is bot or not if it's use this...
....
Oh typo
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
Use it then compare the action with this or smthing
Then
....;-;?
Thenks*
!d discord.AuditLogAction.bot_add
Works too
ah, didnt know that action exists too

you can't, they use discord's oauth to protect user data
using a request won't get you anything
it didn't worked:
env/Scripts/activate.ps1
check the Scripts folder of your env to see if the activate files are even there or not
vanessa 
when i checked up it brings me this:
guess all i had to do is to change script to bin
can someone tell me what are these different types of selects
it's creating linux style venv for some reason lol
probably because you're using virtualenv instead of the built-in venv module
Select is a normal select where you add the options
in others, the select options are added by discord based on the select type
for example UserSelect will list all users in the server
yep, and was it
oh damn
thanks
how do i create a venv file without the linux version?
use venv 🤷♂️
python -m venv env
how to install the windows version of venv?
it kinda erroed here
it comes preinstalled
yeah, it's built in
what version of python do you use?
i kinda updated it but it shows 3.8.9
If not then you can always do pip install virtualenv
how do i delete the old version to use the updated version?
since you're on windows you can delete it form your control panel
or you can mention the full version name if you dont want to delete the old installation
python3.<version> -m venv env
how do i delete the old version
and check the new version?
and then install from official python website
Also this is kinda ot
back to the problem i had before:
await random.choice(guild.text_channels).send("random shit")
their virtualenv message indicated that the created environment was "CPython3Windows" rather than Posix, so something doesnt match up
If I do the following:
owner_ids=[123, 456, etc]
would @command.is_owner(owner_ids)
only give the access to command to the owner_ids?
you don't need to specify owner_ids in is.owner()
so... @command(owner_ids)?
nono @commands.is_owner()
yea if u put it in ur bot instance
yea like in the python file
like py bot = commands.Bot(..., owner_ids=list(id, id, id)
no, you would have to get ur owner_ids from the json.
alr
What does owner_ids do? You can have other people own the bot??
What additional functionality would they get by doing so?
i.e, jishaku, owner/developer only commands, etc
would this also work?
I see
sure
kk ty
it would be owner_ids=OWNER_IDS
So is that how you would do premium commands? Or would that be separate?
it would be cleaner of you to just make the list when you specify owner_ids
owner_id=list(123, 456, 789)
that would be a different check
Bet
?!
This is a good example of using @commands.check()
I see I see
Yeah I'm about to do that nonsense.. people have been asking for a feature that would cost me money so I'm going to make it premium. I don't like making paid features but when I have to pay, I rather make it premium
Fair enough
true
if that's where you're calling client.run, sure
How do I fix this?
class MyView(View):
@discord.ui.button(label="Click to copy!", style=discord.ButtonStyle.secondary, emoji="✔")
async def button_callback(self,button,interaction):
button.label = "Copied!"
button.disabled = True
button.style = discord.ButtonStyle.green
await interaction.response.edit_message(view=self)```
``` button.label = "Copied!"
AttributeError: 'Interaction' object has no attribute 'label'
Switch the arguments around
- (self, button, interaction)
+ (self, interaction, button)
worked now thanks!
Whatever tutorial you follow, don't follow it
I was looking at the python docs
what should I do, as I am trying to learn how to dev in python?
!resources
Resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
there are a lot of free resources for learning python there ^
does anyone know what the problem is? i did everything like in the tutorial and the guy on youtube is online but mine doesn´t work
@vocal snow still at it, absolute mvp.
How do you have so much time, tell me the secret.

Well the first one is that role isn't loaded or just doesn't exists. Second one is that the bot doesn't have permission to do the action inside the command.
where do i enable them? in discord or in replit?
black, extremely dark, freshly brewed coffee 😋
discord developer portal the url is in the error.
Dang maybe that works, I always put some milk in...
yeah its an acquired taste without the milk
I'm very busy with an internship now, else I would def help out more here.
oh cool, python internship?
For the API yes, paired with PostgreSQL + alembic and React, TS + chakra.
Learning so many new things :D
thank you so much it worked 😄
Oh, you bacc in the server, and no that you even remembered.
I’ve been here since July
Internship is 36h/week and 1 day school so doing overtime already.
Saturday and Sunday free :)
Nice, how long do you plan to work there? Or do you want to go from intern straight to developer?
Until May 31th, and most likely going straight to developer.
After this I need to hand in my report of the internship then if that's validated then I've graduated.
that sounds amazing
😔 me with another 3 years of college
it's role needs to be higher than the top role of the user it's adding/removing roles to
are you adding to the server owner
the role you're trying to add needs to be lower than the bot's top role
1 sec let me fix some thigns
@vocal snow
good morning mudkip
wtf
i meant elementary school, apologies
im not that young
Hey guys can you help my with my code it has an Tab error?
you should claim a channel ( #❓|how-to-get-help )
i need to bee a day here
try asking in #python-discussion then, since this channel is for discord bots
the thig ist im trying to code a discord bot
26.01 00:18:40 [Bot] Traceback (most recent call last):
26.01 00:18:40 [Bot] File "/main.py", line 7, in <module>
26.01 00:18:40 [Bot] from music_cog import music_cog
26.01 00:18:40 [Bot] File "/music_cog.py", line 99
26.01 00:18:40 [Bot] self.is_paused = False
26.01 00:18:40 [Bot] ^
26.01 00:18:40 [Bot] IndentationError: expected an indented block
26.01 00:18:41 [PebbleHost] Server shut down (running)
26.01 00:18:41 [PebbleHost] Server stopped
the full is too long
i know it shoud be a tab error but how can i fix that?
!indentation
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Also, we can't help with music bots here
how can i make my bot accept an invite
you can't
yes u can
discord bots cannot accept discord server invites
I assumed you were talking about a normal discord bot, since user bots aren't allowed by discord and we don't help with them here
i mean it is a normal bot till it accepts invite then its a user bot sooooo
it's a user bot as soon as you log in with your user token
that doesnt work


does anyone know how to display username/server name using sqlite db
That's pretty vague, do you have a user/server name inside a sqlite db and you want to retrieve them?
await cursor.execute('CREATE TABLE IF NOT EXISTS users(vouches INTEGER, user INTEGER, id INTEGER, server names INTEGER, server ids INTEGER)')```
basically want server names + user to display as the guild name and user name
rather then an integer
Why is your server name an int
I'm unsure how to make it display as text so I temporarily made it an integer (I'd change it later)
so I could still test the code
Are you sure you can have spaces in field names?
yes, if not I'll just make it server_names
do you know how to make it display text (the server name/user name)?
Set its type as TEXT
And you can't have spaces in the field name because SQLite use that to separate types (to my knowledge anyways)
yeah
alrighty
ok, but discord.py, which requires aiohttp, is listed
should i pay attention to this warning?
andy
no he was typedef not typeset
no
alr
true
also true
real
nope
any ideas on how to fix? Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) File "/root/roof.py", line 247, in on_ready await tree.sync(guild = discord.Object(id=0)) File "/usr/local/lib/python3.9/dist-packages/discord/app_commands/tree.py", line 1071, in sync data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload) File "/usr/local/lib/python3.9/dist-packages/discord/http.py", line 738, in request raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
How can I create a discord bot
well what library do you want to use?
You need to enable application commands scope when inviting the bot
await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
TypeError: object tuple can't be used in 'await' expression```
does anyone know how to fix (sqlite)
You're trying to await a tuple
Not a function
At least try to look where the error occurred
!e
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def main():
await("meow",)
loop.run_until_complete(main())
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
004 | return future.result()
005 | ^^^^^^^^^^^^^^^
006 | File "<string>", line 7, in main
007 | TypeError: object tuple can't be used in 'await' expression
Im a bit confused, how do I alter my code to await the tuple?
Are you kidding me
data = await cursor.fetchone()
if data:
await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
else:
await(cursor.execute('INSERT INTO users (user, id, server_name, guild) VALUES (?, ?, ?, ?)', (f"{member.name} + #{member.discriminator}", member.id, ctx.guild.name, ctx.guild.id,))```
like my bio says, im new to this sorry.
don't be rude
thank you
use cursor.execute like you did in the other part
okay, thank you
a tuple is a data type, cursor.execute is an async function
okay!
i've done this, it's not giving me any callback or errors but it isn't adding the member to the database
Demn
But you didnt commit here?
On the if statement
I have, I just didn't include it here because it wasn't part of the previous callback
do you know what is wrong w it?
Show the full code
its really long but I will cut it down one sec
You need to commit everytime when you want to change something in the database
I have
Hey @spice jewel!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i
one second
msg3 = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
if msg3.content == "y":
await ctx.send(" User removed ")
await ctx.send(embed=remove)
dynamic_timestamp = nextcord.utils.format_dt(datetime.now(), style="R")
removenotice=nextcord.Embed(
title=f"⠀⠀ You were removed ✦",
color=nextcord.Color(0x8d06411)
)
async with aiosqlite.connect("callisto.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute('DELETE FROM users WHERE id = ? AND guild = ?', (member.id, ctx.guild.id,))
await cursor.execute('DELETE FROM pilots WHERE id = ? AND server_ids = ?', (member.id, ctx.guild.id,))
await db.commit()
await member.send(embed=removenotice)```
this is the part which had the previous traceback
can any of u still help w this?
File "/root/pres_d.py", line 6, in <module>
RPC = Presence(client_id)
File "/usr/local/lib/python3.9/dist-packages/pypresence/presence.py", line 13, in __init__
super().__init__(*args, **kwargs)
File "/usr/local/lib/python3.9/dist-packages/pypresence/baseclient.py", line 28, in __init__
raise DiscordNotFound
pypresence.exceptions.DiscordNotFound: Could not find Discord installed and running on this machine.``` any fixes
i have it running on a debian 10 vps so its a ssh.
anyone know how to run a discord.client and a command.bot
please @ me if yk what is wrong.
anyone know?
Choose one
uhhh
If you want to create prefix commands, just use discord.ext.commands.Bot
And delete the discord.Client
alr
can i run events with that ?
Yes
alr cool
Can you print the data?
it's 2023 why are you still using message.content.startswith
the commands extension was introduced years ago
Smort
one second
what could i use then?
the command system
any docs?
or could u send me a command lines for example
an example*
what library are you using
I was reading the doc and saw this:
@bot.hybrid_command()
async def test(ctx):
await ctx.send("This is a hybrid command!")
I have been maaking slash commands like this:
@client.tree.command(name="streak", description="Shows your current streak.")
async def slash_streak(interaction: discord.Interaction):
with open ('data.json') as count:
data = json.load(count)
total_streak = data["streak"]
await interaction.response.send_message(f"Your current streak is {total_streak}")
what's the difference?
still needed
Hybrid gives you both slash and prefix command
commands.HybridCommand is a command that can be invoked as both a text and a slash command.
only this?
It doesn't affect the functionality?
well, i will use hybrid more
No
easy syntax 😅
@client.tree.command(name="streak", description="Shows your current streak.")
#See the difference mate
@bot.hybrid_command()
yes but you can also put that in hybrid_command
Remove the kwargs and it will be almost the same
^
my bad ...
@client.tree.command()
#See the difference mate
@bot.hybrid_command()
oh it's fine 💀 you don't have to do that
@shrewd fjord are u still able to help w this?
what issue are you facing?
hello, so I was experiencing this traceback below
await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
TypeError: object tuple can't be used in 'await' expression```
which has now been resolved
can anyone help me with this im just swithcing over or is there any docs?
but whenever I try to add someone in my database
await cursor.execute('UPDATE stuff whatever')
yes but it doesnt add the user
you can see that if you read the error carefully
Ash ayo
Ive fixed it yeah but now it doesnt do anything and when I get it to print the data it returns none
(after ive run the cmd)
alright
if data is None:
Compare like dat
spooky 🛐
Ehm
async def button6_callback(interaction):
if interaction.user == ctx.author:
view.remove_item(button6)
await interaction.response.edit_message(content="Other added!", view=view)
msgnext = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
if msgnext.content == "next":
await ctx.send("What is there starting vouch count?")
msg2 = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
if msg2.content == "test":
async with aiosqlite.connect("callisto.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO users (user, id, server_name, guild) VALUES (?, ?, ?, ?)', (f"{member.name} + #{member.discriminator}", member.id, ctx.guild.name, ctx.guild.id,))
await cursor.execute('INSERT INTO pilots (pilot_vouches, games, user, id, server_ids) VALUES (?, ?, ?, ?, ?)', (0, f"none", f"{member.name} + #{member.discriminator}", member.id, ctx.guild.id,))
await db.commit()
await ctx.send(embed=embed)```
ive cut down the code a bit
this is the part in my code I was getting the first error, but now when I run the add cmd and respond to the message correctly (test) it still doesn't add the user to the db but it sends the embed
Try,
if data is not None:
Instead of if data:
Wait a sec
okay
You need to use "" this it's the correct format for executing a query
"UPDATE....... ...." like dat
oh I see
^ this doesnt work but ill try what you just said one second
And use single quote on string/text values
Demn
!d sqlite3
Mhm
what should I try now?
instead of ?
^
still no tracebacks, no errors, nothing
just not adding the user
await cursor.execute(f"UPDATE users SET id = {member.id} WHERE guild = {ctx.guild.id}")
alright
Altho it's not recommended, but this is pretty good for testing stuffs
Make sure the data isn't None
I wouldn't do it like this
What's wrong with placeholders
Because it can't update the column if it returns None
I see nothing tbh
But code is working fine but not working
Kinda spooky
....
have a table
Did u create table?
@commands.hybrid_command(
name="profile",
description="Check a player's general information.",
aliases=["p"]
)
```is there any shortcut for when there's only one alias?
@callisto.event
async def on_ready():
print("Online!")
async with aiosqlite.connect("callisto.db") as db:
async with db.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS middlemans(mm_vouches INTEGER, games TEXT, user TEXT, id INTEGER, server_ids INTEGER)')
await cursor.execute('CREATE TABLE IF NOT EXISTS pilots(pilot_vouches INTEGER, games TEXT, user TEXT, id INTEGER, server_ids INTEGER)')
await cursor.execute('CREATE TABLE IF NOT EXISTS users(user TEXT, id INTEGER, server_name TEXT, guild INTEGER)')
await db.commit()```
yes
There is some prob with commit then
how should I fix then?
tried that and it returns a traceback
(doesnt work)
....
** **
Ik i am just bad
HELP
🙂
