#discord-bots
1 messages · Page 1046 of 1
Like what?
but it would still be stuck wouldn't it
before saving the warn you should upload the user and the warn in the json file
also a json file is not great to use so
And how will I do that
still confused here :hmm:
why
Isn’t the code already there for the id
it gets all the messages into a list if they're in a certain channel (because I didn't know what your condition was), then if the time is already more than what you define end_of_time, it exits the wait_for
you are first looking for a member with the id, but since in the json file does not exist you get an error
returning True
where can i find the docs for discord.py v2
Yes so how can I make it dump the id
<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>```
why I'm getting this
with open("warns.json", "w") as file:
data = {str(member.id): warn}
json.dump(data)
however I think this won't work
can't you use a database?
maybe the replit database
No I’m learning to use json
pain
Where do I put this?
u dont need to learn json
Ratelimit
I got to know it's because of free host
Replit
no, railway
We are getting somewhere
It’s dumping the id
But not the amount of warnings
my vs code thing not working ;-;
please i need help about discord.py asap please #help-chili
How would i make it ignore the bots reaction? Only react if its 2 reactions
can i ask a query related to dislash?
Yh
i am using dislash for drop down menus
and i want that when someone clicks in menu bot responds
I am getting this error. Can someone help me?
@slate swan ^^
Long time no help 😦
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
@vale wingcan u help me ?
it's not youtube_dl @vale wing.
With what
It's ffmpeg
Read the error
youtube_dl.utils.DownloadError
i am using dislash for drop down menus
and i want that when someone clicks in menu bot responds
Ytdl related
That library no longer exists afaik
wait what i am using it
I think it was renamed to disnake which is the modern library but I am not sure about that
yeah it is renamed to disnake
And discord to nextcord
but there exists dislash too
No
as new cmds have come
nextcord is better than discord
Idk about it but disnake is better at slash commands implementation
Sorry I have no experience with menus exclusively but ig you can check out examples in disnake repo
Is this in a cog
Then why do you have self
warn is the variable that define the amount of warn
sure you don't want to use the replit database?
i checked i am trying with it but i am unable
What have you got so far
How would I do smth if the channel doesn't let people msg in it
this is in a cog file?
Change channel's perms
Logic
I mean like how would I check if the channel doesn't let people type in it
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member")
or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
TypeError: Embed.set_author() takes 1 positional argument but 2 positional arguments (and 2 keyword-only arguments) were given
embed.set_author('name', url='Embed.Empty', icon_url='Embed.Empty')
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
All args are keyword-only @flint isle
uhh i dont understand
whats keywords
function(kwarg=10)
umm so how do i fix the embed code then? what part is wrong?
oh
thanks
this is my cog, what is wrong in it?
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
print(Fore.GREEN + 'Connected!' + Fore.WHITE)
print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
bot.get_guild(798726719573065749)
channel = bot.get_channel(798726720181633047)
await channel.send('Bot Online!')
embed = disnake.Embed()
embed.title = f"**Online**"
embed.description = f"[`{datetime.datetime.now().strftime('%b-%d-%Y`] @ [`%I:%M:%S')}`]\n\n" \
f"- Bot account: `{bot.user.name}`\n" \
f"- Bot ID: `{bot.user.id}`\n" \
f"- Guilds: `{len(bot.guilds):,}`\n" \
f"- Users: `{len(list(bot.get_all_members()))}`\n" \
f"- Disnake Version: `{disnake.__version__}`\n" \
f"- Developer: `whiskeythefox$7339`\n" \
embed.set_footer(text="Logging System")
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
pass
def setup():
bot.add_cog(events)
cause it wont run that on ready
What error do you get
And do print statements get executed
I suspect you have issue with sending a message to a channel
so i fogot to load it lol and now im getting this error
Developed by: David Powell 0.005
Starting Bot
Connecting to Discord API.
Please Wait
Loading Developer Features cog
Traceback (most recent call last):
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 418, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 879, in exec_module
File "<frozen importlib._bootstrap_external>", line 1017, in get_code
File "<frozen importlib._bootstrap_external>", line 947, in source_to_code
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 31
embed.set_footer(text="Logging System")
^^^^^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
bot.load_extension('cogs.events')
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 421, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (events.py, line 31)
Process finished with exit code 1
line 31 is the footer set one
Issue with another extension
what?
To be certain indent issue
Your embed.set_footer is indented in a wrong way
Also what the hell is that string
"""
Use
multiline
string
please
"""```
oh lmao i will do that when i get to that part
yeah i moved it to right under the title one and it works better now
Also you should bring the constants out
Loading Developer Features cog
Traceback (most recent call last):
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 430, in _load_from_module_spec
setup(self)
TypeError: setup() takes 0 positional arguments but 1 was given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
bot.load_extension('cogs.events')
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 435, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: TypeError: setup() takes 0 positional arguments but 1 was given
Process finished with exit code 1
it this what its talking about?
def setup():
bot.add_cog(events)```
Traceback (most recent call last):
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 430, in _load_from_module_spec
setup(self)
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 42, in setup
bot.add_cog(events)
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 307, in add_cog
raise TypeError("cogs must derive from Cog")
TypeError: cogs must derive from Cog
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\wb.py", line 61, in <module>
bot.load_extension('cogs.events')
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 490, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 435, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: TypeError: cogs must derive from Cog
I don't understand how to do it
You need class instance not a class itself
Well you gotta learn how to understand documentation, nobody will give you ready solution
does it need to be up in the class?
Tbh this documentation is pretty easy to understand in relation to some others
Instance of cog class
idk what your talking about
def setup(bot):
bot.add_cog(SomeCog(bot))```
SomeCog is just a class and SomeCog(bot) is an instance of class, iow an object
OOP 😀 👍
ahh
hmm
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 515, in _run_event
await coro(*args, **kwargs)
File "C:\Users\David Powell\PycharmProjects\WhiskeyBotMain\cogs\events.py", line 22, in on_ready
await channel.send('Bot Online!')
AttributeError: 'NoneType' object has no attribute 'send'
@commands.Cog.listener()
async def on_ready(self):
print(Fore.GREEN + 'Connected!' + Fore.WHITE)
print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
bot.get_guild(798726719573065749)
channel = bot.get_channel(798726720181633047)
await channel.send('Bot Online!')```
thats the affected code
self.bot.get_channel....
ah
it work?
yep just had to add self infront of all the bot.
imagine defining "bot" in the cog file again.
that's how it works in cogs
self.bot = bot
well that code vanished
yh i accidentally sent
i have this:
for channel in ctx.guild.channels:
if channel.permissions_for(ctx.guild.default_role).send_messages==False:
#stuff
and i'm getting this error:
Traceback (most recent call last):
File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Asus User\Documents\Python Practice\Test Bot\test bot.py", line 15, in lock
if channel.permissions_for(ctx.guild.default_role).send_messages==False:
File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 495, in permissions_for
roles = member._roles
AttributeError: 'Role' object has no attribute '_roles'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Asus User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Role' object has no attribute '_roles'
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
string = 'got fined 696,696 again'
List = list(map(int, re.findall('\d+', string)))
await ctx.send(''.join(List))
which fork?
TypeError: sequence item 0: expected str instance, int found
Can someone teach me how to make my own middlemanbot for my new middleman server? Plssssss
🤔
Plss
no spoonfeeding :bruh:
Bro idk anything on bot making that's why bruv
u know python?
...
Idk codinggg
@shrewd apex look at this legend
Bruv
yeah
@slate swan in that case
u have 2 option
- just go to top.gg and invite the bot u want
- learn python fundamental
- look up discord servers where u can hire coders
Im a pro at discord bots I can certainly help you
ahem
a pro that doesnt know how to reverse thing
🤣
ill have you known thats a complex piece of code
just try to do it urself
no seriously speaking u can ask a coder to help u in a collab project
Ill help you:)
no need la just ask here
we all will help
Yes, ill probably be the most help here tbh
but cant guarantee instant reply
ya
I can make u guys staff in server?
sarth hunter sparky immit ashley can help
Or co owner
sure
Sure np
Dm me
i dont think u can add reactions to a msg invoked with slash commands
@loud junco @shrewd apex could you guys go back and help me solve my complex problem
k
LOL
complex question on how to reverse a string
no
Theres much more to that
Uh, no I'm not
Oh hi hunter...
I'm his dad who has gone to get some milk
I'm a pro at coding hunter like I have 12 years of experience
Oh cool
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Uh, no thanks
Alr
Hm I was thinking...
!e
import builtins
class String(str):
def reverse(self):
return self[::-1]
builtins.str = String
print(str("Hi").reverse())
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
iH
Oh works. Cool!
!e
from fishhook import hook
@hook(str)
def reverse(self):
return self[::-1]
print('hello'.reverse())
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
olleh
step 1: learn python
is there a method to get a vc like bot.get_channel
maybe try to fetch the message id and then add reactions
that works?
@app_commands.command(name="test", description="Testing")
@app_commands.guilds(discord.Object(id=845317571301081158))
async def testreason_slash(self, interaction: Interaction, reason: str="Unspecified"):
yep
oh ty
is this correct ?
yes
I swear I hate discord.py's slashes
^
it dosent work for me i had added tht cmnd yesterday
any errors?
yes
what is it
uh-huh that's a slash command how do you get command not found error with that?
!d discord.app_commands.CommandNotFound
exception discord.app_commands.CommandNotFound(name, parents, type=<AppCommandType.chat_input: 1>)```
An exception raised when an application command could not be found.
This inherits from [`AppCommandError`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
New in version 2.0.
rayden did exception for exception
how would that issue even raise 🗿
hm maybe a command which appears on discord but not in the code? ...
most probably when an app command is removed off the discord api but the client hasnt already refreshed and interpreted that the command doesnt exist anymore
yeah that makes sense
gonna call the mods 😔 this time, he just shitposts in this channel like every day ffs
i hv made tht command in a new cog so i need to wait 1 hr ?
everyday?
wow
i see the passion
but wrong place
🤣
no, since you have set the servers to register the cmd in, try doing ctrl+r (discord) and run the command
that works for me
ctrl + r legit breaks my discord
someone trolls me and my discord crashes for 30 mins
you just have a bad omen
took me 30 seconds to get the reference
LOL
i can make anything reference with jojo and mc
no comments
smh
when idk whats programming language
24-hour format 😭
LOL
i can read it
the way we think in math is different ig
:/
maths.......and time?
whats the relation....
anyways........ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
sure'
i'd not just....going to random help channels
how can i get a list of what cogs are loaded?
!d discord.ext.commands.Bot.cogs @flint isle
property cogs```
A read-only mapping of cog name to cog.
lol
Bot.cogs gives you a mapping of cog names to Cog objects
is there a way to just get the name of the cogs?
Bot.cogs.keys()
and how do i remove dict_keys( from the output lol
list()
hmm how do i use that?

like this?```py
list(self.bot.cogs.keys())```
Yea
thanks
list(self.bot.cogs) also works
ur teddy bear
but i thought it will list different thing
they list the same thing
one will list the variable name and one will list the variable value
nope, that would be just the list of keys
hmmm ok
they earlier said they just want the name of the cogs so i suggested cogs.keys()
from the one without keys: ['developerfeatures', 'events']
the one with keys: ['developerfeatures', 'events']
thats the same :p
that would be list(dict.items()) when u iterate over a dict, u basically iterate over the keys, same concept applies for when u do list(dict)
i dont understand but alright
how may i get my bots uptime?
should i send him the uptimerobot
no not that
u mean 247?
like have a command to show uptime right
huh
!e ```py
dictionary = {"A":1, "B":2}
for a in dictionary:
print(a)
for a in dictionary.keys():
print(a)
when you Iterate on a dictionary, the key is taken as the element
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | A
002 | B
003 | A
004 | B
setup a datetime when the bot starts
each time you want to get the uptime, you would have to subtract it from the current datetime
for a,b in dictionary.items():
print(a)
```the one im saying is this right?
that will throw an error
wrong, unless you do dictionary.items()
oo
i found this on stack overflow
would this work for that?
import discord, datetime, time
from discord.ext import commands
start_time = time.time()
@commands.command(pass_context=True)
async def uptime(self, ctx):
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
embed = discord.Embed(colour=0xc8dc6c)
embed.add_field(name="Uptime", value=text)
embed.set_footer(text="<bot name>")
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send("Current uptime: " + text)
how did you define start_time
ooooo okok
there i updated it. does that work?
isn't this stackoverflow-ed
pass_context is very outdated
lemme show a quick example of how you would do the uptime
from datetime import datetime
bot = ...
bot.start_time = datetime.now()
``` now whenever you want to get the uptime you can do datetime.now() - bot.start_time
Is it okay to have 50+ 1 second-loops editing files on the host's computer every second ?
this means 50 file edits every second
won't this make the bot lag alot ?
Does the lag amout scale with the size of the file edition ?
ofcourse, larger the data the more resource usage
bot.guilds
im using client
yes
everything
ok
everything
its discord.ui.Select
not Select
error?
um
try changing the emoji like one above
@slate swan
do you get any errors?
no
of misc*
hm, try using the unicode form of emoji \🛠️
And does all other option appear?
ye ig
i just realized what was missing lmao
nah, pc
Nice lol
install emoji extensions or whatever its just a 🛠️ emoji in unicode form
and how do i take that output into days, hours, minutes, seconds
ye i copy paste in discord chat it show me 🛠️
it does that automatically.
tias
WhiskeyBot [Beta] BOT — Today at 9:29 AM
0:00:09.576231
thats the output lol
What the hell
1 second loops are bad
Generally
Unless you make them better
i use 5 sec loop thats why 💀
Min time I use is 30 seconds
imagine 30 sec late giveaway
1 second loop has a high chance of getting stuck
ye
Before it is able to execute again
ahh the worlds gonna end
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
Just make embed object
Holy cow I see "open_account" again
Who's the author of that tutorial
It's weird af
me
i dont know whats oop(object oriented proggraming)
how does it get stuck ?
Why are custom emojis shown on the server where these emojis were uploaded, but not on other servers?
It doesn't get finished before next interaction
what code to use to get the description of a command by a command
does your bot have the Use External Emoji permission enabled on the server in which the emoji doesn't appear?
Yea
yeah ik but like lets say i have a custom help command where i wanna the user to do !Help <command> and it gets this commands description as well
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get
the subcommand `bar` of the group command `foo`. If a
subcommand is not found then `None` is returned just as usual...
is there a way to make it to the next interaction even if the action isn't finished ? Like a kind of async loop
Enabled for everyone and for the role of the bot and for other roles that the bot has
does this function require cogs as well or no?
I don't really know about loops mechanism implementation in dpy
You want the timer to start when the function starts and not when it finishes?
@vale wing i tried as well but i got no idea how to use it as well
it is bot.get_command nvm let me try again
discord.ext.tasks
The function that runs in the task
oh
await ctx.message.delete()
AttributeError: 'str' object has no attribute 'message'
it works but doesn't get the description of the command as well which is not what i need
any ideass??
Yes, you can do ctx.bot.get_command(...)
well I want a 1 hour timer that does stuff at the end of that hour
Are you mutating ctx? That looks really odd
im not tho thats why im confused
msg = await ctx.send(...)
await msg.delete()
yes but what i want is get the description or the info about the command i set
and its deleting the message but still sending the error
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def monkey(ctx, banana):
await ctx.message.delete()
await dh(f"{ctx.author} ran monkey command!", f"banana: `{banana}`")
await monkey(banana, ctx.author)
Unhandled exception in internal background task 'timer'.
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\tasks\__init__.py", line 157, in _loop
await self.coro(*args, **kwargs)
File "c:\Users\hp\Desktop\bot\giveaway.py", line 71, in timer
for keys in logs2.keys():
RuntimeError: dictionary changed size during iteration
..
@tasks.loop(seconds=10)
async def timer(self):
with open("giveawaytime.json") as f:
logs2 = json.load(f)
for keys in logs2.keys():
😐
Once you have the command object you can access that in the attributes
and how
This doesn't show what's inside of the loop. That's what is important
For example cmd.description or cmd.brief
ok i fixed it, i had a function called the same as the command
your log2 dictionary added/removed an element during the iteration, and python doesn't like when you do that
example for this in code because i'm not able to understand using this
Have you seen this before? There's examples here: https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
so
@tasks.loop(seconds=5)
async def timer(self):
with open("giveawaytime.json") as f:
logs2 = json.load(f)
for keys in logs2.keys():
a = logs2[keys]
b = datetime.fromisoformat(a[0])
if b <= datetime.now():
a1 = a[1]
a2 = a[2]
await self.endgiv(int(keys),int(a1),int(a2))
del logs2[keys]
with open("giveawaytime.json","w") as s:
json.dump(logs2,s)
So you'd get the command and set it to some variable like cmd = ctx.bot.get_command('echo') then you can do like print(cmd.description)
Yeah look it's right there: del logs2[keys]
Yeah, that modifies the dictionary
ill suggest to clone the dictionary and use it for iteration
You should do the opposite: create a new dictionary with only the keys you wish to keep
if i clone iwd need to edit that too
im confused
@slate swan
but i want to compare the time
use that dict only for the for loop checker?
yeah ty
how can I send a message in chat off a slash command without it being counted as a reply?
discord.Interaction.channel.send
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
and use the send method on this
thanks
i restarted discord today but its not shown
today....as in before making that command, right?
yes i made tht cmnd yesterday and restarted today
uhuh
like it doesnt show up or what
colors = ["yellow","red", "blue"]
@bot.command()
async def delete_role(message):
userrole = message.author.roles
user = message.author
for x in colors:
if x in userrole:
role = discord.utils.get(user.guild.roles, name=x)
await message.author.remove_roles(role)
await message.reply("role deleted")
else:
await message.reply("i cant find any role")
return```
i want to code something that deletes the every role user have in the colors list
but bot always says i cant find any role
can somebody explain me why?
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note
that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’
role.
These roles are sorted by their position in the role hierarchy.
Basically you're comparing a string to a role object
Which would never be true so it triggers the else block
my bot itself is not shown
sad
Hi dear
I played exploding minions
rip
wow
irl?
oh, cool
is there a way to execute a bot command through code ?
Well
What does this error mean second image is my json
What do you meab by "through code" first
i am having problem with easy pil
when i call Font().popins(size=30) it gives me an error TypeError: __init__() missing 1 required positional argument: 'path'
i am trying to use the static method of the class i tried multiple ways but no luck
its not letting me send a rank card
for example when I do the /help command, the bot executes the /show_help_embed command and also executes the /admin_call_help command
even though the user didn't type in /show_help_embed nor did he type /admin_call_help command
no thats not possible
I remember a method that can tho
Wait does it exist
i mean u can import the function and edit it a little bit 🤷♂️
!d discord.ext.commands.Context hold on lemme just search the docs
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about
the invocation context. This class is not created manually and is instead
passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
what library are you using
idk then, generally i'd just get the .callback of the slash command object and pass in the interaction to it
!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/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally...
@paper sluice
woah huge
Slash comamnds dont work on context.
thanks @supple thorn
Oh is it slash commands?
👀
How the fuck did i remember this
/ yea
what are you using for slash commands then?
I mean that could just be his prefix
unless they have / as their prefix
@small sentinel is / your prefix?
Then you can do it
ah , the just use bot.get_command("command name").invoke()
yup thanks
Damn my brain working overtime
Context.invoke will just invoke the main command
I was gonna check discord.ext.commands but i went with context instead
unless the command is passed
Cause it seemed right
Can you please tell me which intents should be called separately for PRESENCE INTENT or SERVER MEMBERS INTENT or both?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
do it this way
for member intents, intents.members=True , for presence intents.presence =True
thanks you
How do I activate members.intent?
class client(commands.Bot):
def __init__(self):
super().__init__(
command_prefix='.',
intents = discord.Intents.default(),
application_id = 770696433573036054)
self.synced = False
async def setup_hook(self) -> None:
self.session = aiohttp.ClientSession()
folders = []
files = []
target_dir = Path.cwd() / "cogs"
for file in target_dir.rglob("*.py"):
folders.append(file.parent.name)
files.append(file)
print(folders)
print(files)
for ext in folders:
for num in files:
try:
await self.load_extension(f"cogs.{ext}.{num.stem}")
except:
pass
await cltree.sync(guild = discord.Object(864993787835056138))
self.synced = True
async def on_ready(self):
await self.wait_until_ready()
print(f"Logged in as {self.user}")
aclient = client()
cltree = aclient.tree
aclient.run(os.getenv("TOKEN"))
sigh, just enable all of 'em 😔 ease
discord.Intents.all()?
yeah
if I do that i get an error saying I didn't activate them on the discord devs
but I did
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
💀 nu, never
intents=(
hikari.Intents.ALL_UNPRIVILEGED
| hikari.Intents.GUILD_MEMBERS
| hikari.Intents.GUILD_PRESENCES
),``` my intents
@slate swan
wait, whats left then?
you didnt turn that on from the dev portal
DM_MESSAGES, GUILD_MESSAGES
member intents is off from what i see.
every time i turn this intent on after I reload the website it deactivates 
indeed, slash commands save the day
You need to turn off the first and turn on the second
that's why I cant do discord.Intents.all()
if i somehow am able to get them i just need to add the lightbulb.PrefixCommand in all the implements decorator lmao
💀 perks of using lightbulb.
yep
@slate swanNow everything is correct, why the error?
make sure its the right bot.
This is the right bot
Is there a simple way to prevent a list turning into NoneType when its last value gets removed ?
because right now I have a list, and when I remove the last element of that list, it turns into a NoneType object
are you using .remove or .pop ?
I use .remove to remove elements of that list
what the hack?
>>> 968269079339216960 == 968269079339216960
True
async def webhookHandler(self,webhookobj,message):
o = webhookobj.data.data["obj"]
chid = o.webhook.hook.data.data["channel_id"]
d = o.webhook.hook.data.data
print(d)
print(message.channel.id == chid,end=f": {message.channel.id} == {chid}\n")
if message.channel.id == chid: return await o.process_command(message,message.content,message.channel)
output
False: 968269079339216960 == 968269079339216960
that doesn't make any sense
try #python-discussion this isn't the channel to discuss the specifics on why .remove does that
no need i found out why i am getting this
{'type': 1, 'id': '975001492291461170', 'name': 'Minecraft', 'avatar': 'd454ac7282327357452c16d0bfbf882d', 'channel_id': '968269079339216960', 'guild_id': '968269079339216957', 'application_id': None, 'token': '8kxkLa2Flu3op5OlKY5U3oJljHKqFFAJzUVmSVYwjf18k5F7FT-KI_5Q9GszsveQCy-c'}
Why
Also did you just show the token
Of the webhook
lol
this discord webhook is unava
Ok
okay sry
well his error was saying his class didnt have an attr of message lol
Yea
https://paste.pythondiscord.com/yemoloreti
File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Users\a\Desktop\GD Verify\bot.py", line 25, in first_button
account_id = response.json()[accountID]
KeyError: 0```
i do not understand why this returns keyerror: 0
no such key
accountID is literal to 0
so its value is 0
and theres no such key lol
hm
i have a question, in my code
i do a request to https://gdbrowser.com/api/profile/
!e
key = 0
d = {1: 2}
print(d[key])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | KeyError: 0
ok to an api?
does it take what i put in
/link blablabla
and puts in https://gdbrowser.com/api/profile/blablabla
?
well it depends on your code you can yes with f strings
does my code do that? https://paste.pythondiscord.com/yemoloreti
if yes, then the code thinks accountID is 0?
well it is 0
and its never been mutated
and here you should make username a kwarg
inter, *, username: str
so it would take all text after the slash
forgot about that trick lol
but it's supposed to, where is it not working do you think?
ohh wait
nvm
well here youre just indexing the payload with the base account id which is 0 which is incorrect
i recommend you print the payload and then index it correctly
this is what happens when you dont do python for a while
i figured it out
ty for the help
@slate swan
youre welcome!
how does a member enter the bot cache
Why am I getting this error
bot = commands.Bot(command_prefix=".")
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
it depends really
are you using pycord?
I used to but I uninstalled it using pip uninstall py-cord
What the
any way to do it purposefully?
I don't want to use pycord anymore, just discord.py
yes
Wdym
Wdym by purposefully
as in I want to get a member in the cache without using fetch_member
Do you mean intentionally?
you can access the bots cache yes, i would need to check its source code to see how the bot caches the members
yes
Use get
member
if you use get it searches the cache
i think they ment add the member or get it?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
this relies on the member already being in the cache but I want to do this without a member already being in the cache
well how does a member get added to the cache
Somehow getting a member from the cache without the member actually being in the cache and not fetching the user
Iirc usually they're added automatically when the bot connects
Fetching the user using fetch_user
Also puts the member in the cache
I mean if the user interacts with the bot and somehow gets added to the cache that would do great
So you can get the member by get_user
@autumn surge https://github.com/Rapptz/discord.py/blob/b7e25645dc68bbb828bf1ede711d098c6b183237/discord/state.py#L333-L342 heres the method that adds the member
discord/state.py lines 333 to 342
def store_user(self, data: Union[UserPayload, PartialUserPayload]) -> User:
# this way is 300% faster than `dict.setdefault`.
user_id = int(data['id'])
try:
return self._users[user_id]
except KeyError:
user = User(state=self, data=data)
if user.discriminator != '0000':
self._users[user_id] = user
return user```
dpy first parses the user in another method and then they use this to save the parsed user
I see ty, do you know which methods use this one?
some methods below do
alright I'll have a look ty
let me give you an example
how can i check if a user snd the bot a dm?
This should do it?
@cltree.command(guild = discord.Object(864993787835056138), name="testing_command", description="Comando para pruebas.")
async def test(interaction: discord.Interaction):
await interaction.response.defer(thinking=True)
for user in interaction.guild.members:
print(user.name)
Im trying to get all the members in a server
But only get one and it's the bot itself
the method _add_user() os more suiting in this case
you can check if the guild is none
if not ctx.guild:
...
alrighty thank you
youre welcome!
or you can go for the faster check
if ctx.guild is None:
...
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yeah but look at the code above it
class client(commands.Bot):
def __init__(self):
super().__init__(
command_prefix='.',
intents = discord.Intents.default(),
application_id = 770696433573036054)
self.synced = False
self.intents.members=True
well do you have them active in the portal?
yeah
property guild```
The guild the interaction was sent from.
member count works
was it in a dm?
nope
because the property can return None if its in a dm but i doubt it because you would get a Nonetype error
tbh i dont really know whats your problem everything looks fine to me
Hi
I forgot how, I know okimii probably remembers
I want to make a welcome bot with pyrhon
yeah it's kinda weird 
like set what user avatar?
im a bit confused on the wording
yes
Does someone wanna help me making welcome bot with python
yeah
its an avatar command i suppose?
I don't remember what it's caleld
pretty sure this is against tos
so you want to make an image with the users avatar?
How if I may ask?
no, like set the author embed with the users avatar
spamming?
@bot.event
async def on_member_join(member):
try:
await member.send("Welcome ")
except:
pass```
Well, it's not in a public discord.
I'm the only one in it, I just want to check vanity urls.
like with the set_author method?
still Im pretty sure it breaks discord tos
well youre spamming post request to the api lol
Alright, fair enough
Lemme see?
What about this
??
TypeError: fetch_guild() missing 1 required positional argument: 'guild_id'
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
im a bit confused on what you want sorry😅
wouldn't it be client.get_guild(ID)
show full traceback
What would go in the None though?
Fetch is api request and get is from cache
ahh
ctx.author.avatar.url
If on icon
so...
Just icon_url=ctx.author.avatar_url
what am i doing wrong in here?
await client.fetch_guild(864993787835056138)
discord.app_commands.errors.CommandInvokeError: Command 'testing_command' raised an exception: TypeError: fetch_guild() missing 1 required positional argument: 'guild_id'
Tried that and got this
discord.app_commands.errors.CommandInvokeError: Command 'testing_command' raised an exception: TypeError: fetch_guild() got some positional-only arguments passed as keyword arguments: 'guild_id'
sure
This is my command
I could do interaction.guild.members but If I do that for some reason I get only one member and it's the bot itself
Show where u define client
No
self.fetch_guild
You need an instance of that
bot = Client()
Also you should make class names PascalCase so it isn’t the same as variable names
oh so it should be aclient.fetch (?
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@bot.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
# Daily stuff
#####
bot.event()
async def reset_daily():
now = datetime.now()
reset = datetime.strptime('23:59', '%H:%M')
if now == reset:
daily.reset_cooldown()
Is this correct somehow? And how do i reset the cooldown for everyone from the server?
I want the daily command reset every day at 23:59 or 12pm like that
Not sure about the cooldown stuff
enabled from the discord developer site too?
yup
damn that's weird
Yesterday, I had asked about manually triggering an event (in my case, I'm looking to trigger the on_member_join event. So they suggested:
Bot.dispatch("member_join", Member)
But I can't seem to quite figure out what the second parameter Member needs to be. I tried to create an instance of Member:
test_member = discord.Member()
bot.dispatch("member_join", test_member)
But that wasn't right.
So then I tried:
bot.dispatch("member_join", discord.Member)
And that seems to half work? It doesn't error, but I get odd results.
Just wondering if someone can help me figure out how to set Member correctly.
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
Use this to get the Member object
Thanks! I'll give that a try!
yeah and make sure you have member intents enabled
do !intents here if you dont know what it is
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yep! I've got it set on the gateway as well as in the code. I think I have that bit working, but good call!
so I'm doing this in my "on_ready" and when I provide my own user_id
test_member = discord.Guild.get_member(user_id=user_id_int)
I get an error about missing a positional argument:
TypeError: Guild.get_member() missing 1 required positional argument: 'self'
do I need to get the guild first?
you would need an instance of a Guild object yes
!d discord.ext.commands.Context.guild
Returns the guild associated with this context’s command. None if not available.
if youre using a command with context then you can return an instance of a guild object with the guild attribute
ok, let me fight with this some more. Thanks! 🙂
youre welcome
Well, still can't figure out why I can't get all memers from the server and only the bot itself
class client(commands.Bot):
def __init__(self):
super().__init__(
command_prefix='.',
intents = discord.Intents.default(),
application_id = 770696433573036054)
self.synced = False
self.intents.members= True
async def setup_hook(self) -> None:
self.session = aiohttp.ClientSession()
folders = []
files = []
target_dir = Path.cwd() / "cogs"
for file in target_dir.rglob("*.py"):
folders.append(file.parent.name)
files.append(file)
print(folders)
print(files)
for ext in folders:
for num in files:
try:
await self.load_extension(f"cogs.{ext}.{num.stem}")
except:
pass
await cltree.sync(guild = discord.Object(864993787835056138))
self.synced = True
async def on_ready(self):
await self.wait_until_ready()
print(f"Logged in as {self.user}")
aclient = client()
cltree = aclient.tree
@cltree.command(guild = discord.Object(864993787835056138), name="testing_command", description="Comando para pruebas.")
async def test(interaction: discord.Interaction):
await interaction.response.defer(thinking=True, ephemeral=True)
print(interaction.guild._members)
aclient.run(os.getenv("TOKEN"))
This is my full code
How to send an image to discord using pillow without saving the image
Can anyone help me building a welcome message bot if so then dm me
from io import BytesIO
with BytesIO() as image_binary:
img.save(image_binary, "PNG")
image_binary.seek(0)
file = disnake.File(fp=image_binary, filename="image.png")```
You helped me a lot, thank you very much
Can someone send me begging of index.js
no worries, i ran into the same issue with mine
this is python discord server
Do u have js server?
speakjs is one
I still don't seem to be getting it
current_guild = commands.Context.guild # This is a cached_property, and has no get_member()
test_member = current_guild.get_member(user_id=user_id_int)
bot.dispatch("member_join", test_member)
So commands.Context.guild is a cached_property and therefore doesn't seem to have a get_member() attribute:
test_member = current_guild.get_member(user_id=user_id_int)
AttributeError: 'cached_property' object has no attribute 'get_member'
I'm not sure what I'm doing wrong (obviously I'm not understanding something). I should also mention the function are async in case that matters? I had been seeing things on StackOverflow talking about an async branch of discord.py being different, but they were a little older so I wasn't sure if that was still relavant?
!d disnake.Interaction
class disnake.Interaction```
A base class representing a user-initiated Discord interaction.
An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.
New in version 2.0.
hey ive been running into this error
Traceback (most recent call last):
File "/home/toasty/.local/lib/python3.10/site-packages/interactions/api/http/request.py", line 171, in request
raise HTTPException(data["code"], message=data["message"])
interactions.api.error.HTTPException: Invalid Form Body Error code: 50035
@bot.command(
name="minions",
description="Information about Slayers",
options=[
interactions.Option(
name="username",
description="Minecraft username",
type=interactions.OptionType.STRING,
required=True,
options=[
interactions.Option(
name="profile",
description='profile name',
type=interactions.OptionType.STRING,
requered=True), ], ), ], )
the last options is the error
it does not crash when i remove it but i need it
how do i stop it from crasing
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
what is the best module for buttons in discord.py ?
just use builtin buttons
@bot.command(
name="minions",
description="Information about Slayers",
options=[
interactions.Option(
name="username",
description="Minecraft username",
type=interactions.OptionType.STRING,
required=True,
options=[
interactions.Option(
name="profile",
description='profile name',
type=interactions.OptionType.STRING,
requered=True), ], ), ],
Traceback (most recent call last):
File "/home/toasty/.local/lib/python3.10/site-packages/interactions/api/http/request.py", line 171, in request
raise HTTPException(data["code"], message=data["message"])
interactions.api.error.HTTPException: Invalid Form Body Error code: 50035
just import button
@quaint epoch just import button
no
just to know exactly how to search for information on these buttons
for example ```py
import discord
class view(discord.View):
@discord.ui.button(label="button", style=discord.Style.green)
async def callback(self, button: discord.Button, interaction:discord.Interaction):
# do stuff
@bot.command()
async def foo(ctx):
await ctx.send(view=view())```
@quaint epoch just don't give me the documentation site from discord.py
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
!d discord.Button
class discord.Button```
Represents a button from the Discord Bot UI Kit.
This inherits from [`Component`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Component "discord.Component").
Note
The user constructible and usable type to create a button is [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Button "discord.ui.Button") not this one.
New in version 2.0.
couldn't you just check the docs yourself?
@quaint epoch no!! don 't do this !!!
@quaint epoch this site pisses me off
don't like the site
which site?
it's not my fault that there are so few synonyms for words in English
okay it doesn't seem related to your question
yes. it's not related, it's just a request not to throw off the link to the website with documentation!!!!!!"
well, you asked for documention
oh you said don't
well, i also provided an example
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
okay?
If i change dictionary_name size while looping through enumerate(dictionary_name): will it throw an error or is it creating a new object
lets see
!e dict = {"hello": "hello", "there":"there"}
for i in enumerate(dict):
dict["world"] = "world"
@quaint epoch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | RuntimeError: dictionary changed size during iteration
!e
dict = {"hello": "hello", "there": "there"}
for i in list(enumerate(dict)):
dict["world"] = "world"
@dull terrace :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'python' is not defined
!e
dict = {"hello": "hello", "there": "there"}
for i in list(enumerate(dict)):
dict["world"] = "world"
@dull terrace :warning: Your eval job has completed with return code 0.
[No output]
oh, so you need to create a new object
there's that
now im gonna go brush me teeth, cya
and gn
gn
!e
dict = {"hello": "hello", "there": "there"}
for count, i in list(enumerate(dict)):
print(count, i)
for count, i in enumerate(dict):
print(count, i)```
@dull terrace :white_check_mark: Your eval job has completed with return code 0.
001 | 0 hello
002 | 1 there
003 | 0 hello
004 | 1 there
The docs aren't "shitty" tho, they work quite well
well, it's just as good as an ass that has diarrhea
Eh...
I'm not? Edit: reply to message where you said something along the lines of "don't change your mind"
Is there a way to specify how many servers per shard?
That's not what I meant, just a translator, a fucking translator.
it's just that everyone here when they see Russian begins to write rules 4. Just infuriate such bitches
They write it because it's a rule 
just in this way, the server shows its worthlessness. Since most of the server understands that they are too stupid to understand Russian at all
holy mother of god i've made this piece of code messy
if player.guild not in guild_gen_rank:
guild_gen_rank[player.guild] = {player.id: (player.username, player.generated)}
else:
temp_ggr = list(guild_gen_rank[player.guild].items())
for count, tup in list(enumerate(temp_ggr)):
generated = tup[1][1]
if player.generated > generated:
temp_ggr.insert(count, (player.id, (player.username, player.generated)))
count += 1
for count_two, data in list(enumerate(temp_ggr[count:])):
ind = count + count_two
if data[0] == player.id:
del temp_ggr[ind]
break
guild_gen_rank[player.guild] = dict(temp_ggr[:3])
break```
trying to keep only the top 3 people in the dictionary who have the highest player.generated
afaik, the rule 4 is based on moderation and stuff. Since most of people can understand English, it's picked as the server language making moderation, discussion, etc. easier . And since I'm not part of staff I can't say with 100% accurate that it would be exactly like that.
if you were the staff you would have already given me muted
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
I called them stupid in that message
off-topic, and not related to me
Is there a way to make a command to get all discord member, example:
This Server has (member count) user
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and
accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified...
guild.member_count where guild should be a Guild object
should be*
guild.member_count
This would be all the users a bot can see
list = [apple, banana, orange]
i need to make list look like that without making them string, how can i make it?
Maybe use str then .replace(“‘“, “”)
colors = ["yellow", "red", "blue"]
@bot.command()
async def delete_role(message):
userrole = message.author.roles
user = message.author
for x in colors:
if x in userrole:
role = discord.utils.get(user.guild.roles, name=x)
await message.author.remove_roles(role)
await message.reply("role deleted")
else:
await message.reply("i cant find any role")
return```
Doesn't stringifying that do that exactly?
i want to use it on that code
so that wont work
whats that?
!e
mylist = ["apple", "banana", "orange"]
print(str(mylist))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
['apple', 'banana', 'orange']
Like that without the quotes, you say?
!e
mylist = ["apple", "banana", "orange"]
print(f"[{', '.join(mylist)}]")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
[apple, banana, orange]
like that?
yay
but how can i use it on that code
i mean that
name=', '.join(colors))
Like that
it didnt work
Also there are a few things flawed here
it sent i cant find any role
can you show it please?
i dont know much about coding
Idk how to use proper quotes on mobile
😭
sorry
Hi guys, is there any way to do this kind of things using a python library ? I'm using discord.py & discord_components for Button & so but I can't find any library that allows me to do this
- commands take
ctxas the first argument, notmessage if x in userroleyou're checking if a string is inside an iterable ofdiscord.Roleobjects
discord.py can do that
I'd suggest not using discord_components
If u upgrade to discord.py v2 you get buttons and this and app commands
- if x in userrole you're checking if a string is inside an iterable of discord.Role objects
how can i fix it?
Good to know, I'm going to check it, thanks 🙂
You can use a list comp to map role objects to strings
[role.name for role in user.roles]
if "role name" in [role.name for role in user.roles]:
# user has the role
im stupid lol
so i should write every role name
after and after
Not really, it can be x in your case
colors = ["yellow", "red", "blue"]
for color in colors:
if color in [role.name for role in user.roles]:
# user has color role
Would be better to only do the list comp once I think
Fair point
what does comp mean?
@bot.command()
async def my_command(ctx: commands.Context, ...):
role_names = [role.name for role in ctx.author.roles]
list comp = list comprehension
[x for x in range(1, 5)] is an example.
It’s like dynamically creating a list
!e
fruits = ["apple", "banana", "orange"]
print([fruit[0] for fruit in fruits])
@sick birch :white_check_mark: Your eval job has completed with return code 0.
['a', 'b', 'o']
for example
it's getting too complicated
It's like map(), but faster
why would i need to get first letter of role
You don't, it was an example to demonstrate list comps
oh
You could optimise it even more with sets, ```py
colors = {"yellow", "red", "blue"}
names = {r.name for r in roles}
if names.intersection(colors):
# has
In your case, instead of getting the first letter of each item in a list, you want to access a certain attribute of each item in a list (role.name)
Beauty of hashes
I was going to suggest that haha
cant you guys explain it like im 10
colors = {"yellow", "red", "blue"}
names = {r.name for r in roles}
if names & colors:
# user has role
doesn't change much but looks nicer imo
cuz im new to python and i cant get every part of your words
Okay, what are you confused on?
Okay, let's take that apart part by part
look at this part first:
for role in ctx.author.roles
That's basically going to go through each item inside ctx.author.roles (which is a list, btw), and assign that to the role variable
Next part is the first part: role.name for ...
Basically that says: "take each item in the list, get the .name property of it, and put it inside a new list"
umm dude it didnt worked
@bot.command()
async def delete_role(message):
user = message.author
colors = ["yellow", "red", "blue"]
for color in colors:
if color in [role.name for role in user.roles]:
role = discord.utils.get(user.guild.roles, name=', '.join(colors))
await message.author.remove_roles(role)
await message.reply("role deleted")
else:
await message.reply("i cant find any role")
return```
code looks like that
and i got that error
theres nothing like "id"
did i miss something
Full traceback please?
In [1]: def foo() -> None:
...: Role = type("Role", (), {"name": "blue"})
...:
...: names = {r.name for r in [Role() for _ in range(100)]}
...: colours = {"yellow", "red", "blue"}
...:
...: if names.intersection(colours):
...: ...
...:
In [2]: def bar() -> None:
...: Role = type("Role", (), {"name": "blue"})
...:
...: names = [r.name for r in [Role() for _ in range(100)]]
...: colours = ["yellow", "red", "blue"]
...:
...: for colour in colours:
...: if colour in names:
...: ...
...:
In [3]: %timeit foo()
12.6 µs ± 231 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
In [4]: %timeit bar()
14 µs ± 262 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
You're sure that's 100% everything?
The role is None so get couldn’t find the role with the name
how can it be possible
the issue is that you're passing all the role names separated by "," when trying to get the current match. Instead of say, looking for "yellow", it'd look for "yellow, red, blue"
a role named "yellow , red , blue" ?
change ", ".join(colors) to just color
Why even use the name? Why not just use IDs
With that you'd be able to use get_role as well, which is faster than utils.get
Just need to change the colors list to a list of role IDs, corresponding to the colour of course. Then just change the list comp to use role.id instead of role.name, then just do Guild.get_role(color)
Hey hello
anyone knows why this happens every time I turn on my bot?
TypeError: 'type' object is not subscriptable
bro you are so professional and noticing even 5% of what you are saying will be very painful for me
so please
dont do it

