#discord-bots
1 messages ยท Page 153 of 1
code:
async def onegai(ctx: commands.Context, channel_id):
vc = discord.VoiceClient(bot, channel_id)
vc.connect()
vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
while vc.is_playing():
await asyncio.sleep(.1)
await vc.disconnect()
await ctx.respond("Please pound me more with you ")```
error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: VoiceClient.connect() missing 2 required keyword-only arguments: 'reconnect' and 'timeout'
xd
or actually use a discord.VoiceaChannel typehint
ffound this from pycord docs
alternatively you can do
channel_id = int(chanel_id)
he said not working with int too ๐คท
yes but it will make the bot join in the vc in which the author is
skill issue
hm
hm cool
kind of knew that ๐
did but stil gave the error "int doesnt have connect"
vc = await voice.channel.connect()
vc.channel.connect according to pycord docs
its coro btw
voice_channel.connect, not chanel_id connect
from here ^
after replacing this
my guy using big brain w
new code:
@bot.slash_command(description='Joins Voice Channel And Play Onegai Sound Effect')
async def onegai(ctx: commands.Context, channel_id):
channel_id = int(channel_id)
voice_channel = bot.get_channel(channel_id)
vc = voice_channel.connect()
vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
while vc.is_playing():
await asyncio.sleep(.1)
await vc.disconnect()
await ctx.respond("Please pound me more with you ")```
new error:
vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
AttributeError: 'coroutine' object has no attribute 'play'
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
it's coro ๐คท
altho
whos coro?
you didn't await the connect thing
ohh
it's maybe voice_channel.play
i think xd
after connecting
im my Library would be as easy as ```py
await bot.gateway.update_voice_state(serverid, channel id)
w
me nub dev
hmmmmm I dont think so since we already defined vc as voice channel
imagine creating own wrapper and customize it as u wish looks cool
maybe lol idk anything about connecting to a voice channel
๐ you can help by contributing tho
i am noob dev 
business
there's a todo for things easier than you can imagine
and im too lazy for them
IS THERE 2 + 2?
as easy yeah
;-;
cul
but 2+2 = 5 so hard ;-;
what, its 22
altho in my higher math exam i kinda fked up in the calculation
9+3-2=10 right but i was kept thinking 11 kinda bruh
then after a lot of big brain using real cal culator i realized it's 10 ๐
ike wtf
nah dawg its 11*2 
carry a python with you at exams so you can do basic maths calc using it
oh nvm
can someone tell me who is coro?
now tell me how to contribute 
coroutine
a coro is a coroutine, basically an async function
you know any git basics?
async =await
git needs basics? sheesh
soo my code is giving error because the vc didnt get awaited
i only know how to serch stuff and how to steal imean learn
just cloning, commit and push is enough
search*
i can teach you if you wanna learn
await vc.play
or vscode makes it easier
i can use
you didn't await .connect
but win 7 doesnt support py ;[
await voice_channel.connect()
yeah great I'll dm you some easy tasks that you can work on
I did
hmmmmmmmmmmmm
this ^
hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
now it joins vc which is nice but no sound and giving error of this
await vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
AttributeError: 'VoiceChannel' object has no attribute 'play'
ctx.voice_client.play
ok\
How to make different time for cooldown for each person using database, for example one user has 20 minutes, another 25?
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`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") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
what do you use instead of "ctx" when using slash commands?
interaction
interaction.author.id doesnt work. how would i do that?
interaction.user
They don't have the exact same attributes and methods
where can i make the list of options?
guys I need help asap
what
bot = commands.Bot(help_command=None, command_prefix="2?", intents=discord.Intents.all())
I did this but it still doesn't remove the help cmd and I keep getting error
discord.ext.commands.errors.CommandRegistrationError: The alias help is already an existing command or alias.
its defult help cmd from discord commands
how do I disable that?
youve done it right, with help_command=None
so why doesnt it work?
show full code?
async def help(ctx):
HelpEmbed = discord.Embed(title="Here are all the commands", color=0x2ecc71)
HelpEmbed.add_field(name="Basic Predictor Commands", value="2?towers, 2?crash, 2?casemode (casemode is just for fun")
HelpEmbed.add_field(name="Premium Predictor", value="everything from basic predicator and 2?mines + 2?bloxflip.")```
remove the aliases=[]
OH THAT
function name defined the command as help
you dont need to do that
bot = commands.Bot(help_command=None, command_prefix="2?", intents=discord.Intents.all(), case_insensitive=True)
you can use that instead
!e discord.ext.commands.Bot
@stone quest :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'discord' is not defined
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.

@rare echoyooo
what does this error mean?
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'claim' raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
i get this erroe when i run this code: https://pastebin.pl/view/7e50eb31
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
Not full tb
!paste also use this
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this is the full tb
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 490, in pay
await cursor.execute("SELECT user_name FROM claim_data1 WHERE user_id = ?", (USER_ID,))
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'claim' raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
What's type of user_id col in db and what it is in USER_ID?
USER_ID is the sql variable and the user_id is the actual id i get from the author of the command
I asked about their types
int
Why would you save a username in a database?
@regal cove send me CREATE TABLE instruction for that table and print(type(USER_ID))
idk i decided to do that and i guess it doesnt really matter
I mean it adds a lot of variables, for instance, what if I change my username?
If he/she is in 2 servers with a custom username, what will it use?
await cursor.execute("""CREATE TABLE IF NOT EXISTS claim_data1(
num INTEGER NOT NULL PRIMARY KEY, user_name TEXT,
date INTEGER,
streak INTEGER,
user_id INTEGER NOT NULL
)""")
num? is the pk ๐ hmmmmmmmmmmmmmmmmmm
i understand that it would be a problem if they change their name. but i believe you can only change your nickname on different servers
True, but still you can change the username.
you're right i should probably remove the user_name thing
i will do that but i just wanna solve the error first
Also consider using user_id as pk since that is unique.
Lol
alright
@regal cove and what about USER_ID type
i believe that should be int aswell
i will double check that hold on
Print it anyway
BIGINT ๐ฟ
Nah it fits.
hm lemme check
263 - 1
In sqlite there's no such thing as explicit BIGINT, it automatically expands the INTEGER field size if needed iirc
2 to the power of 63
i believe i forgot to convert USER_ID to int
9223372036854775807
Why some weird const when you can ctx.author.id
Well in a db it's a good way to save extra user data.
Where does USER_ID even come from
i use slash commands
so i cant use ctx
So what
interaction.user.id
Same stuff.
And let's pray it stays that way.
Name of the parameter doesn't affect anything
As long as it's instance of Interaction everything will be working
oh i understand
bruh i could probably have done what you said but now i've edited so much of my code its easier to just let it stay that way
Nah better to name it inter/interaction cause good practice
py-cord ๐ณ
I guess you could use discord.ext.commands.Bot.get_context and make a custom context to add database support and have really clean commands but eh, clean AND useful, let's not...
Stawph
I mean
no
๐
thank you guys
frustration or wot ๐
i now know what mistake i made. the problem was that i did interaction.user instead of interaction.user.id
๐ฑ
do you know what IndexError is
can someone help me with making persistent views for select menues
can you tell me if i did something wrong by looking at my code? i will send you my code in dm
how do you delete a message when using slash commands
i dmed you
check your messages requests maybe
for the decorator's option argument
i am using a for loop to append select options in the list
but i cant figure out where to run the loop
like in discord.ui.Select class i ran the loop after super() to append options
What? Don't persistent views have to have custom id?
No the opposite.
I mean you can if you use raw requests but it's meant so that you can't have conflicting stuff happening.
Hi, any of you guys good with discord bot developing? Like actually good
Best to just ask the question rather than asking if there is someone that could solve it.
the question is long
i just wanna say im an amateur that is looking to get something done with the help of someone
the plan is big
Okay, people are here to help with problems etc. but we aren't providing any kind of "assistance", you do still need to code it yourself. Sometimes we do provide small examples.
Any of you guys good with discord bot developing?
Like I said above, you will most likely not get a different answer. Just ask the question.
Okay then and I'm gonna specify the question.
I need a python bot that runs on discord and has different commands users can use. That bot needs to log in a users instagram's account feed, give the user an option to fill the password area, username 2-fa etc. and when it logs into the instagram, user can choose a refresh second interval from 1-10seconds. The bot then needs to refresh the instagram feed based on the interval the user chooses and everytime there is a less than 60 seconds old post it needs to comment one of the comments we set on the comment list and many other features.
A friend of mine send me a 'skeleton' or like asample of that code but I need to work on it with someone. This plan
is really big trust me
Instagram userbots are surely against TOS
But it is not an instagram userbot
log in a users instagram's account feed, give the user an option to fill the password area, username 2-fa etc. and when it logs into the instagram
is it not? ๐ค
huh
i thought view mush have custom id to be persistent
no what it does is that it self promotes
on new posts
Like there is no botted comment likes, no botted coments it's just self promoting the account
You've seen many memepages do it on comment sections
via userbotting...
Indeed they are.
yeah no, you're not gonna get any help on that here
Depends if you are going to utilize the API. Not too sure what exactly you want but if it falls under https://developers.facebook.com/docs/instagram-basic-display-api/ then it's fine.
@cloud dawn
i am confused
Well they aren't set, purely to avoid getting issues down the line.
so i shouldnt set them for persistent views?
yep
and they said its same as buttons 
class Role_Select(discord.ui.Select):
def __init__(self, ctx, roles_list):
options = []
super().__init__(max_values= max_val,min_values=min_val, options=options)# -> options
options = []
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
self.append_option( discord.SelectOption(label=role.name))
options.append(discord.SelectOption(label=role.name))
async def callback(self, interaction: discord.Interaction):
roles = []
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
roles.append(role.name)
user = interaction.user
await interaction.response.send_message("๐ Thinking....", ephemeral = True)
await interaction.delete_original_response()
for item in roles:
role = get(ctx.guild.roles, name= item)
if item in self.values and role not in user.roles:
await user.add_roles(role)
elif role in user.roles and item not in self.values:
await user.remove_roles(role)
Options = []
class DropdownSelectView(discord.ui.View):
def __init__(self):
super().__init__(timeout= None)
self.add_item(Role_Select(ctx, roles_list))
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
Options.append(discord.SelectOption(label=role.name))
@discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
async def select_callback(self, interaction: discord.Interaction, select):
roles = []
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
roles.append(role.name)
user = interaction.user
await interaction.response.send_message("๐ Thinking....", ephemeral = True)
await interaction.delete_original_response()
for item in roles:
role = get(ctx.guild.roles, name= item)
if item in select.values and role not in user.roles:
await user.add_roles(role)
elif role in user.roles and item not in select.values:
await user.remove_roles(role)
can someone tell why its still not persistent
you don't seem to be adding any custom IDs. Your Options list should be inside the class (as a class variable)
pandabweer said persistent wont work if you add custom ids
should i use global here?
I'd differ
No, inside your constructor, you access Options with self.Options
!d discord.ui.View.is_persistent Then the docs or wrong 
is_persistent()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)"): Whether the view is set up as persistent.
A persistent view has all their components with a set `custom_id` and a [`timeout`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.timeout "discord.ui.View.timeout") set to `None`.
๐คท
Send your whole code please
so i should set custom id or not? 
You should set them, yes
class DropdownSelectView(discord.ui.View):
def __init__(self):
super().__init__(timeout= None)
self.add_item(Role_Select(ctx, roles_list))
@discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
Options = []
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
Options.append(discord.SelectOption(label=role.name))
ok cool
You'd typically set class variables after you define the class' name
So, above __init__
and loop too
above init?
No, your loop should stay where it previously was (inside the constructor), the select decorator should be above the select's callback, and Options should be in between the class definition and __init__. You can also set the options before you instantiate the super class
class DropdownSelectView(discord.ui.View):
Options = []
def __init__(self):
for item in roles_list:
if isinstance(item, int):
role = get(ctx.guild.roles, id=item)
self.Options.append(discord.SelectOption(label=role.name))
super().__init__(timeout= None)
self.add_item(Role_Select(ctx, roles_list))
@discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
async def select_callback(self, interaction: discord.Interaction, select):
like this?
Well, roles_list isn't defined anywhere
but sure
yeah its not here
but it exists ๐ฟ
Anyway, tias ig
i am getting 2 drop down menus
Yup
self.add_item(...) -> Adds a new component to the view
@discord.ui.select(...) -> Also adds a new component to the view
imma remove self.add_item
will it fix?
sure
well
working fine but not after restart
means still not persistent
Maybe see this example of a persistent view: https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
:incoming_envelope: :ok_hand: applied mute to @timid spade until <t:1670771135:f> (10 minutes) (reason: newlines rule: sent 104 newlines in 10s).
The <@&831776746206265384> have been alerted for review.
yikes
!unmute 764775571833749519
:incoming_envelope: :ok_hand: pardoned infraction mute for @timid spade.
thanks
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/hanifadito what does this code do? its from a tutorial and im new to coding#
Where specifically
when i run it
The way they generate a random string is funny
ew
so it does nothing?
idk i got it from google but cant remember where
Probably for spamming message to a channel 
Possibly
whats that?
Discord account automation
it steals? like a tokenlogger?
no, it automates stuff on your Discord account, it's also against TOS
sure, but use a good API wrapper like discord.py if you want to code Discord bots
ok thank you
why does this only dump one person in the json file?
@tree.command(name = 'initiate_bans', description='This will activate the economic ban system')
async def ban_all_members(interaction: discord.Interaction):
if interaction.user.id == (767636284083666971):
await interaction.response.send_message("Bans have been initiated", ephemeral = True)
ban_list = {}
for guild in client.guilds:
for member in guild.members:
ban_list[member.id] = ban_balance
print(ban_list)
print(interaction.user.id)
with open("ban_data.json", "w") as outfile:
json.dump(ban_list, outfile)
else: interaction.response.send_message("Sorry but you dont have permission to perform this command.")
what does ban_list print out as?
consider using an actual db instead of a json file too
yeah i know that but the ban feature wont be used much so i cant be bothered to migrate such a small thing. the rest of my bot uses sqlite
Because you're not reading the current ban list before you dump the new one
"w" mode puts the cursor at the start of the file
When you write to it it's gonna overwrite whatever is already in there
You should be
- read json file into dictionary
- update dictionary
- dump dictionary into json file
Oh nvm you mean you want that to happen but only 1 guild member is dumped?
else send message isn't awaited
@bot.tree.context_menu("whothis")
async def whothis(interaction: discord.Interaction, member: discord.Member):
embed = discord.Embed(title=f"{member.name}#{member.discriminator}", description=f"ID: {member.id}")
embed.add_field(name="Joined", value=member.joined_at.strftime("%a, %d %b %Y %I:%M %p UTC"), inline=False)
embed.add_field(name="Roles", value=", ".join([role.mention for role in member.roles]), inline=False)
embed.add_field(name="Badges", value=", ".join([badge.name for badge in member.public_flags.all()]), inline=False)
embed.set_thumbnail(url=member.avatar_url)
await interaction.response.send_message(embed=embed, ephemeral=True)
I get the error ```py
CommandTree.context_menu() takes 1 positional argument but 2 were given
why
!d discord.app_commands.CommandTree.context_menu
@context_menu(*, name=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command context menu from a regular function directly under this tree.
This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User"), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message"), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)") of `Member` and `User` as its second parameter.
Examples...
All arguments are keyword only
You don't have to add a name if it's gonna be the same as the function's name either
thanks man
Does look better with it tough.
i want everyone on the server to be dumped on the json file but only one is being dumped
But why is the function called ban_all_members?? @regal cove
because this is a ban feature
its a feature that will allow the user to ban people from my economy system
Where is ban_balance even comming from?
ban balance is outside the function and that does work. ban_balance is just = 0
now im getting an error with the embed avatar stuff
and then if ban_balance is == 1 the bot wont allow you to use its economy commands
Replace _ with .
Why not add them to the list if they are banned or not rather than adding all members.
thanks
because i didnt think of that lol
but does that actually change anything? the ban command used to work but when i migrated it to using slash commands it stopped working
Then you could have a structure like json { "267624335836053506": [767636284083666971, 169790484594556928], "336642139381301249": [427969521152950284] } string being the guild id and the ones in the list being banned users.
hello, could someone help me figure this out, im trying to display a users banner
@bot.command(aliases=['bann', 'bn'])
async def banner(ctx, *, member: discord.Member = None):
user = discord.Member
member = await bot.fetch_user(user.id)
if not member:
member = ctx.message.author
banner_url = member.banner.url
em = discord.Embed(color = discord.Color.from_rgb(0, 0, 0), title = "avatar link", url=banner_url)
em.set_image(url=f"{banner_url}")
em.set_author(name=f"{member}", icon_url=f"{banner_url}")
em.set_footer(text=f'Requested by {ctx.message.author}', icon_url=f"{ctx.author.banner_url}")
await ctx.reply(embed=em)
i dont think i can do it as easily as with an avatar
@bot.command(aliases=['av', 'pfp'])
async def avatar(ctx, *, member: discord.Member = None):
if not member:
member = ctx.message.author
userAvatar = member.display_avatar.url
em = discord.Embed(color = discord.Color.from_rgb(0, 0, 0), title = "avatar link", url=userAvatar)
em.set_image(url=f"{userAvatar}")
em.set_author(name=f"{member}", icon_url=f"{userAvatar}")
em.set_footer(text=f'Requested by {ctx.message.author}', icon_url=f"{ctx.author.avatar.url}")
await ctx.reply(embed=em)
where this worked fine
that would be great but is there any way for me to fix the code i have right now?
member = await bot.fetch_user(user.id)```please remove these lines completely
replace icon_url=f"{ctx.author.banner_url}" to icon_url=ctx.author.banner.url
well okay done that
still dont know how to get a users banner tho
why did that get deleted?
You'd need to create a good file it's hard to tell without knowing the structure.
The same.
Just don't use underscores that's old code.
how ๐ง
AttributeError: 'Member' object has no attribute 'add__roles'```
Where can I learn discord.py
You put two _ instead of 1
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
LOL, I thought fonts were wide on console
yo isnt that from glowstiks vid
i agree
is there any way my bot could run a / command upon a keyword in chat?
like the only solution i found was to do
@bot.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == bot.user:
return
if message.channel.name == "general":
if "release" in user_message.lower():
await message.channel.send_message(f'run /faq')
but i would rather have it run the / command instead of telling the user to run it yk?
The command has to be a hybrid command or message command.
!d discord.ext.commands.Bot.get_context then get the context
await get_context(origin, /, *, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message or interaction.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
Note
In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
!d discord.ext.commands.Context.invoke then 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...
so would i do ```py
if "release" in user_message.lower():
await invoke(interaction, "faq")
faq is the command im trying to use
Not that easy.
id try the discord.py server TT
Can someone show me an example of a properly initialized client = discord.Client() please?
if "release" in user_message.lower():
ctx = await bot.get_context(message)
await ctx.invoke(discord.utils.find(lambda m: m.name == "faq", bot.commands))
Rough estimation since no clue how hybrid commands react to this.
I'll code the most up to date version
syntax error, need help
The function
@tree.command(name = "username", description = "Generate a random Username")
async def username(interaction):
#code here
The error
async def username(interaction):
^
SyntaxError: invalid syntax
Info:
Visual Studio Code Insiders, 3.8.2 64 bit python, Code Runner
@bot.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == bot.user:
return
if message.channel.name == "general":
if "release" in user_message.lower():
ctx = await bot.get_context(message)
await ctx.invoke(discord.utils.find(lambda m: m.name == "faq", bot.commands))
heres the entire code in case.
but im getting an error saying TypeError: 'NoneType' object is not callable
import asyncio
from discord import AutoShardedClient, Intents
class MyClient(AutoShardedClient):
def __init__(self) -> None:
super().__init__(intents=Intents.none())
async def setup_hook(self) -> None:
print("Setup hook")
@staticmethod
async def on_ready() -> None:
print("Ready!")
async def main() -> None:
client = MyClient()
async with client:
await client.start("token")
if __name__ == "__main__":
asyncio.run(main())
``` This is a barebone setup
Could you provide a screenshot of that part of the code?
You don't need any intents, just a bare object is fine.
If you are making a slash command bot you don't need any intents in fact to make it work.
error
Traceback (most recent call last):
File "main.py", line 27, in <module>
asyncio.run(main())
NameError: name 'asyncio' is not defined
Edited.
@cloud dawn
What is above this function? Issue may be there.
Blank if or blank for usually does this
Hey @untold bay!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@cloud dawn
guys i am losing my mind
I don't see anything wrong.. could you maybe copy the decorator and the async def line? Not the whole function just that. And paste it here?
can someone help me with a command thats like an avatar one but with peoples banners
@tree.command(name = "username", description = "Generate a random Username")
async def username(interaction):
@cloud dawn
i give up on hybrid commands
Uhhhh... I think it might have gotten worse... maybe? https://paste.pythondiscord.com/ipokogadad
restart your ide
Told you it wasn't easy.
i had this issue for about a week
then that won't help
but ill try
It all looks fine.. must be something somewhere that's giving you this issue..
Indentation does look a bit off, maybe that's it?
where is it off?
Well the "token" part does need a valid token.
if message.channel.name == "general":
if "release" in user_message.lower():
# empherial message
await message.channel.send("run / faq", ephemeral=True)
now im trying to make this message emphemeral and i get TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'
Only interaction can send ephemeral messages
yeah i figure, how can i make this ```py
@bot.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == bot.user:
return
if message.channel.name == "general":
if "release" in user_message.lower():
# empherial message
await message.channel.send("run / faq", ephemeral=True)
an interaction
Make a slash command probably
There isn't a way to make a message into an interaction.
Or just DM the user
i fixed the indents still doesnt work
Is it a lot of code? If it isn't I could debug it a bit.
This function has 47 lines
so not sure
I meant the bot.
149
the token should be correct.
The token wasn't being received, but I've fixed that and now I've gotten this error: https://paste.pythondiscord.com/velepuyoqi
case "show":
log_finder = {"_id": inter.guild.id}
log_check = await inter.client.settings.find(log_finder)
print(log_check)
if log_check is not None:
if "log_id" in log_finder:
print("log_id passed")
try:
print("try passed")
log = inter.guild.get_channel(int(log_check['log_id']))
embed1 = nextcord.Embed(title=f"{config.DiscordOwnerBadget} Log Channel",
description=f"<#{log.id}>\n `ID: {log.id}`",
colour=config.blurple)
await inter.response.send_message(embed=embed1, ephemeral=True)
except (nextcord.NotFound, KeyError):
await inter.response.send_message(embed=deletet_channel_info, ephemeral=True)
else:
embedc = nextcord.Embed(title=f"{config.DiscordError} No Log Channel found!", description=f"I could not find any Log Channel for `{inter.guild.name}`",
colour=config.red)
await inter.response.send_message(embed=embedc, ephemeral=True)
if log_check is None:
error = nextcord.Embed(title=f"{config.DiscordError} This guild has no log channel.", description="Please add a log channel",
colour=config.red)
await inter.response.send_message(embed=error, ephemeral=True) ```
He is always jumping to py if log_check is None: but log_check is not None
log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}
Using repl.it i see
Yes? Is there some particular problem with using repl.it?
Well that
You are being ratelimited.
what this mean
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')]
Im on vs cod
with vscode? I use the python extension so i ont have 3,8 installed
@cloud dawn
Does the ratelimit prevent it from working properly? or just make it slow?
Are you on MacOS by chance?
It prevents your bot from working at all
You've been basically blocked from discord
yes i am
I'll take that as a yes..?
I see...
Go into your "Python" folder in your Applications folder, and double click the "Install Certificates" or w/e it's called
u need to manually install the certificates iirc
iim on vscode i dont have python folder
Open up Finder
Click on "Applications" on the left bar
You should see a "Python" folder in there
Inside the "Python" folder there should be a file called something like "Install Certificates"
Double click on that to run it
ok thank
still no work
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/certifi-2022.12.7.dist-info'
Consider using the --user option or check the permissions.
@sick birch \
run as administrator if thats a thing
I'm not much help with MacOS but maybe try with sudo or elevated privledges
class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
All lookups are via the global user cache.
The lookup strategy is as follows (in order)...
If this is in a command it can be even simpler by just type hinting it.
async def test(ctx: Context, user: discord.User) -> None:
user will auto convert using the user converter using the same lookup strategy.
if user_message.lower() == 'coinflip':
variables = ['heads', 'tails']
await message.channel.send(random.choice(variables))
the code runs fine but when i say coinflip it only says heads, so how can i get it to update while its running
using discord.py anyone know why my command isnt working?
# Initalizing bot commands
bot = commands.Bot(command_prefix="?", intents = discord.Intents.all(), activity=discord.Game('Baking a pie!'))
@bot.command()
async def hello(ctx):
await ctx.send("Hello!")
theres more to it of course, but these are the parts I think are relevent
Move the defer to above the purge
Hello!
I am making a tickets bot for a friend and was wondering how to do something
code:
guild = ctx.guild
adm = guild.get_role(ADMIN_ROLE_ID)
ownr = guild.get_role(OWNER_ROLE_ID)
ticket_owner = inter.user
if select.values[0] == "P":
ticket = await guild.create_text_channel(name=f"ticket-{ticket_owner}-purchase")
start_time = datetime.now()
await ticket.set_permissions(ticket_owner, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
await ticket.set_permissions(adm, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
await ticket.set_permissions(ownr, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
await ticket.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False, view_channel=False)
I want it so after the user clicks the button it shows as thinking or whatever how would I do something like that?
It is an interaction : discord.Interaction
hey does anyone know how to make like a 24 hour countdown?
ex:
Refreshes in: 23:59:14
and it just edits and counts it down everytime
Use loops
what are some good hosting websites?
oh use the datetime <t:1670798011:R>
Can someone help me out with this
how do i do that?
<t:1670798011:R>
Traceback (most recent call last):
File "c:\project-spot\main.py", line 40, in <module>
@bot.tree.command(name = "purge", description = "Purge's a channel messages", required = True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: CommandTree.command() got an unexpected keyword argument 'required'```?
required?
yes
Whats the point in using multiple files for your discord bot rather than doing it all in one?
Like what are the advantages and disadvantages
Traceback (most recent call last):
File "c:\project-spot\main.py", line 40, in <module>
@bot.tree.command(name = "purge", description = "Purge's a channel messages")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 889, in decorator
command = Command(
^^^^^^^^
File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 393, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\transformers.py", line 832, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\transformers.py", line 791, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
am i just stupid
It's more organized and readable. It's also not just that the bot is generally better.. since most people aren't coding it correctly if they do it all in one file. Multi file also allows for better hot reloading.
can anyone send me their purge command, i can't find a answer
just remove required
Does that mean I should switch to multifile? I generally do it all in one for ease
should be required by default no?
i did
show code
^
And what should I be splitting it to like one file per command or wha
how do i make my bot check if the content isnt a id then sent to send a message saying send a id
why do you have ctx and interaction?
Well issue is that code quickly gets to 1k lines.
i'm not sure how to purge via interaction
Categorized usually.
Just interaction
example categories?
interaction.channel.purge(limit=amount)?
Also whats wrong with 1k lines
utility, fun, misc
No like dont use ctx
Oh I see,
what do i use then
Interaction
yes?
ok ty, i just switched over to slash commands so im experiencing new stuff xd
np
Nothing if you're coding properly still.
Slash commands doesnโt use ctx it jses interaction
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
I sort of like it, it makes me feel like Iโm doing alot lol but I definitely want to make a configurations file for when I make bots for others
Sync?
Show the purge command.
Also i dont think @lavish micamands.has_permissions works with slAsh commands
You should edit the permissions in the integrations menu for slash commands
Well if you do use cogs then adding cogs for specific peoples needs without coding the whole base again certainly speeds up the process.
it hasn't gave me a error
or anything related to it
What specifically are cogs
Configs?
A message command check for a slash command?
Fat noob here
is that what you guys are talking about? are all your commands in one big ass file?
Cogs are like groups of commands usually.
Not me saying that already
hm?
Oh I think I know what you mean
My discord bot is one file
D:
I was just wondering what the advantages and disadvantages were of not doing that
Might as well oneline it
im praying its not that large
Cring
800 lines ish
ok thats not too bad
I like coding in one file
speaking in terms of amount to transfer
I structure it so related commands are near each other
For example the rep command is above the repleaderboard command
but why not have individual files relating to itself?
Well if you are going to code bots for others coding just a really good base and just build cogs on top of it what they need is more efficient than removing chunks of code everytime you make a new bot.
one file, 6 commands related to x- second file, 9 commands relaying to y- etc.
I code brand new bots for everyone kekw
a lot more manageable
can anyone send their purge slash command please ๐
Experienced dpy coders being busy with the bot base 95% of the time and 5% coding the commands.. 
Yeah like I would make a file for rep and put all rep commands in there
The bot base?
are you still having issues with it?
yes
whats the error?
Well if you have the base and code on top of that you'd update all their bots at once keeping them up to date and also keeping their specific commands per bot.
i might have missed it if you already sent
So you mean like I make a base bot with a bunch of common functions and then just add commands for specific people?
i might be wrong but this is just a sync issue, no?
i'm not sure
- i'm not experience with slash commands
404 from a slash command
Like a really good base to build upon? Hell yeah a lot of bot coders do that, well, who know what they are doing that is.
I usually make bots to fit their specific needs
throw in a debug guild id, then test it to see if its a sync issue
am i doing something wrong?
But it would be cool if the bots I made came already with like moderation and stuff
Then if it breaks you'd need to help everyone at the same time since discord suc
idk i dont use tree or wtv that it x)
How to get rate limits
cant help ya there
Dont sync on ready
Not everyone wants that.
They wouldnโt have to use it
Or they could disable the module
Sometimes a good bot just has 3 commands that can actually perform them really good.
well where else do i sync
Make a sync command
make a command to sync
like /sync?
Preferably a prefix command
setup_hook guys
Like -sync
i wouldnt use a slash command to sync slash commands
then .sync?
Sure
okay
setup_hook?
smells like extra work
It is
Ohhh I see what you mean now
The base of the bot is things included for everyone
And its one file itself
So if I update it I just send the new file to everyone
I think I see what you meant now
Well it would update automatically but you're seeing more clearly now.
oh it purges but doesnt send message and just spits out that error
Just charge a subscription lmao
The thing is each bot I create is sort of unique
Its for each individual persons needs
The command and events right?
probably trying to get z without it being done?
Yeah
They are tailored to the persons needs
What do those have to do with the base?
The base is just useful stuff and initializing the bot.
We'll actually bot.start if we're talking ethics.
Breh
I think I know what you mean though, I think, but the bots I make are also usually for a single server
So there isnt much initialisation
Unless im completely wrong and still dont understand
I mean heck you can code a single bot that has different command and events for each guild.
I mean yeah you could LMAO
but I usually give the source to serber owners so it can be their bot application
Unless im working with the server in a direct way
But i think i have the understanding of base doen
Like the bit where you getGuildID fill in variables with the right content etc
The configuration for a specific server
I'd use c# for the ultimate bots, I'd prob be a billionaire.
But it has a GUI
(Im too stupid to use it(I havent tried))
And you can add graphs
Base releases.
Hehehaw
Updates
In unity yes
Smh
c# used for a lot of apps.
I need to learn java, not for discord coding but just because apparently its a good language to know
java is ok
It has alot of usage
Just all of android is based on it lol
Where it spreads to websites and games and loads
websites and games?
Javascript
nahh
It's the end boss
Like wtf
Nah rust is worse
Me not understanding at alll
cant rust literally println?
C++ is something you would definitely take a course in
Rust can do a lot of things but sometimes too much.
You want a teacher not a youtube video
I just want my docs thanks :3
Bro reads the docs to learn a new language
No one can teach it better than the guy who literally made it and has a written documentation.
I love python and all but the job opportunities it takes you down are really limited
Online it all says data analytics
Which sounds really boring
AI, ML, Security
ML?
Lots of automation inside companies.
Also AI is python based?
machine learning.
Oh fair
It can be.
Me about to work for amazon fresh stores using python
anyone know how to do these "choices" thing? as the tutorial I found didn't work out, it says AttributeError: 'Bot' object has no attribute 'choices'
bot declaration:
intents = discord.Intents().all()
bot = commands.Bot(command_prefix = prefix, intents = intents)
command, I'm trying to make:
@bot.tree.command(name = "pc")
@bot.choices(choices=[
bot.Choice(name="create", value="create"),
bot.Choice(name="set", value="set"),
bot.Choice(name="update", value="update"),
bot.Choice(name="delete", value="delete"),
])
async def pc_slash(interaction: discord.Interaction, command: bot.Choice[str]):
pass
app_commands has choices
Ill be back later see you guys thanks for the help
oh, alright ty :D
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
Click on the link for examples.
hmmm now I get unknown parameter given: choices :/
but I'll test around a few things maybe I find the problem
Did you check the examples?
yea, and when I copy one in, that works, so now I'm trying to change it to mine one step at a time to see where it decides to not work :D
I found it, it was a naming error from my part, didn't realize I need to name two things the same
yo
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
Yo dawh
how exactly is that a bad thing lol
imo the more an language can do, the better it is.
The abstraction level of a programming language used for a project should depend on the user and application.
Some users like low level languages, while some use low level languages due to the lack of abstractions making it easier for them, some people use high level languages to make there life easier or to have set of rules they like or libraries/platforms the language may have.
Actually a lot are made using C# because that's the language Unity uses.
Games also use C++ due to unreal engine!
Yes, but it's actually a variant (Unreal C++).
Mhm thats interesting, what does the general unreal engine use?
wdym?
https://github.com/FallenDeity/PokeLance
planning to publish this as a package just completed the base yesterday any feedback?
Well, you said only a variant of unreal engine uses C++, so what does the general/main one ig? use?
I dont really know much about games๐
No, no, no. UE uses a variant of C++ called "Unreal C++".
Crazy, you even got the @sick birch examples,
https://github.com/FallenDeity/PokeLance/blob/master/examples/basic_usage.py#L16
examples/basic_usage.py line 16
return None```
Ahhh, sorry๐
i am going to report you
๐
ah yeah i still have to create a few usage examples for tutorials docs currently only code is documented
why so much explicit imports from the same directory?
https://github.com/FallenDeity/PokeLance/blob/master/pokelance/cache/cache.py#L9-L56
mypy strict
Smh, just like andy, you guys both want to see the world burn
i had all declared so first time i did wild import but mypy wanted explicit so i just went ahead and did it
cant you just use group imports?!?
or does mypy not like that eitheir
didn't try
It probably does since you've already done them in multiple modules
i was using ruff for linting so ruff didn't like the way mypy import it preferred the * import and mypy vice versa so just muted ruff there
From an overall view, seems like allot of abstractions none the less
Abstraction is the name of the game here
in the models yeah but lots of endpoints
Go abstract a good example robin
๐
bro this is cancer
๐ just from pokelance important models
and use models.Class
@shrewd apex ^
maybe later after i am done with docs and all too much to type ๐
I'll do it before publishing
it's literally just find and replace
why you don't use from __future__ import annotations? this would allow you to specify your classes not as strings but with the class name itself
mhm I'll add it this evening
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
placeholder = "SELECT PAYMENT METHOD", # the placeholder text that will be displayed if nothing is selected
min_values = 1, # the minimum number of values that must be selected by the users
max_values = 1, # the maximum number of values that can be selected by the users
options = [ # the list of options from which users can choose, a required field
discord.SelectOption(
label="Name 1",
description="OPTION #1"
),
discord.SelectOption(
label="Name 2",
description="OPTION #2"
)
]
)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")
What do I need to add to give an output when the option is selected?
the param order of callbacks is self, interaction, select
thank you that worked
Guys what difference between
bot.start() and bot.run()
And which one should I use?
ill suggest using bot.run because it enables logging and stuff by default
you also won't have to use a Seperate asyncio
run with it
Ok
Guys why i getting error
no module named 'cogs'
This is my code
import discord
from discord.ext import commands
import os
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or(">"),intents=discord.Intents.all())
async def setup_hook(self):
print("i am ready")
for cog in os.listdir("rustcomp/cogs"):
if cog.endswith(".py") and cog.startswith("_"):
try:
load = cog.replace(".py","")
load = f"cogs.{load}"
await bot.load_extension(load)
except Exception as e:
print(e)
bot = botclass()
you dont have a folder named cogs in your cogs folder do you
Yep
rustcomp/cogs/cogs doesnt exist as a module
I have file called _rust_compiler in it but that's empty
dont go into cogs twice
Where am I going twice?
i think so as well he should have cocks folder
what's your cwd?
hahahahaha
i mean I have it as well , like i have a lot of cocks folder
thats so funny
I am not going into cogs twice
I am formatting the string with cogs. there
Means file directory
Oh cwd = current working directory
Yep
ig it's rustcomp
@app_commands.command(name = "mylist", description="A list of shop commands!")
async def mylist(self, interaction: discord.Interaction) -> None:
for command in self.bot.commands:
print(command)
Anyone know how to make a list all current commands thats using CTX + app_commands with cogs? The online exampls arent working for me
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
oi how can i hardcode the role names?
i was trying to make a bot change its presense every 10 second to show the ram usage
import asyncio, discord, sys, os, psutil
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import CommandNotFound
activity = discord.Activity(type=discord.ActivityType.watching, name=f'Memory Usage : {psutil.virtual_memory().percent}%')
intents = discord.Intents.all()
client = discord.Client(intents=intents, activity = activity)
async def status_task():
global activity
while True:
await client.change_presence(activity)
await asyncio.sleep(10)
@client.event
async def on_ready():
await tree.sync()
print('Logged in as')
print(client.user.name)
print('------')
client.loop.create_task(status_task())
but i got this error :
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientโs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
It only takes keyword arguments
Also, your presence won't change because you've only defined the activity once but never changed it, so it's pointless to try to change it every 10 seconds
hello everyone, i have a question. I saw this gist.github https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#file-1-primer-md and i don't understand what's the difference about sync with goup and sync without group
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
What do you mean?
you type them manually instead of using the discord.py cache ( ctx.guild.roles)
i am taking role id as input from user
so i should take role name instead?
if its consuming any input from a command how will it be a persistent view lol
you'll have to run the command everytime you restart the bot
ouch
then how tf bots like slash bot manage to do it
theres sync with guild and sync without guild
they don't use discord.py like persistent system but something simpler ig, i can imagine doing this:
user invokes the command wih guild ids:
you make a simple view with role names added in the select.
and the you can use an on_interaction event with checks that adds the role based on the role names...
i might be very wrong when i say that :p
actually wait there's some open source bots that use this lemme check
afaik with libraries like discord.js, you only get that interaction_create event so it becomes your responsibility to know what the interaction is meant to do
yeah but if there's like 10-15 select-roles setup ( that they're doing ) it would be hellish to begin with
yeah definitely should use the builtin RoleSelect class for that
wish discord allowed to limit the roles that show up there
what's the best way to cycle through all members? 
How can I make a bot have a custom profile picture for a specific guild like dyno can with dyno premium
all members in the bot, or all members in a guild
dyno premium uses seperate bot apps for each premium color iirc
if you look into the tags of normal and premium bot it's different
await bot.user.edit(avatar=YOUR_URL_HERE) ?
that edits the global avatar
in a guild
!d discord.Guild.members , requires members intents
property members```
A list of members that belong to this guild.
you can use a for loop on it
ok perfect, then I'll just check which of them have added a reaction to a message 
!d discord.Reaction.users :)
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
I wonder if it's better in this way
for all users
if have addded reaction to message && other stuff
then do Y
or do the opposite
search all the users that have added reaction to message
if other stuff
do Y
But like each individual server can have its own profile picture for the bot
So does dyno create a new application for each server?
the latter
And considering how big it is would it not get limited
or maybe they make you do that. mee6 does the same
They make you make the application and then put in the token
Cant the bot token give access to your discord account or something
Thats the warning discord gives me when I try to send my bot token in a message on discord
nah
mee6 asks for your bot token in order to create a custom bot, maybe dyno does the same
i guess maybe
maybe it was mee6 that i saw with a custom avatar
8 bots i.e.
something like this?
@bot.command()
@commands.has_role("Botmakers")
async def players(self, ctx):
channel = self.bot.get_channel(channel_id)
message = await channel.fetch_message(message_id)
users = set()
for reaction in message.reactions:
async for user in reaction.users():
users.add(user)
await ctx.send(users)
Get all the users that, in a specific channel, have reacted to a specific message
obvs channel_id and message_id are defined 
wonder why the bot tells me that the command "players" doesn't exist 
looking like u r using cog
I put that into the main "cog" 
here
.
@commands.command()
@commands.has.....
like dat
all the others commands in the same .py work though 
can u show the start of that file?
btw why u using self?
self doesnt make any sense on normal commands
๐ค
leave it i already found out
Used to... ๐
remove self
it's normal command
also make sure to restart the bot 
Oh yeah, using the restart command
giving your bot token merely allows other users to control your bot, but it is possible for someone to do certain actions as you if you leak the client id+secret instead
https://discord.com/developers/docs/topics/oauth2#client-credentials-grant
hopefully u fixed it xd
They were right, discord.js is better innit? ๐คก
you don't need to switch language for that
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
use this
Anyone pls help me
seems like it can't fetch the message 
@bot.command()
async def players(ctx):
author_roles = ctx.author.roles
if any(
role.name in {"Botmakers", "Admin", "Moderators", "Staff", "Lead Devs"}
for role in author_roles
):
channel = bot.get_channel(channel_id)
message = await channel.fetch_message(message_id)
print("message ok")
users = set()
print("users created")
for reaction in message.reactions:
print("reaction")
async for user in reaction.users():
# if user.role != "Player":
users.add(user)
await ctx.send(users)
I checked the message_id [I set it manually at beginning of file] and it's correct 
wait imma check for u
from the doc it seemed like that was the way to write that 
is it int?
the id
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
is message_id = 1000324697663209502
or
message_id = "12121212112"?
๐คทโโ๏ธ
ik, but it will work with a string as well
it makes an api request which can be in form of str or int
Python integers can be arbitrary size, there is no effective limit
oh cool
strange the channel fetching is right, but not the message one 
does the bot has perms?
yes the bot has all perms needed [admin] 
Then the message is too old maybe
well the message is very old indeed

5 months
try checking with new message id for test
I thought older 
2-3 weeks is the limit maybe
nah, that ain't the problem 
BRUH
I thought I said that 
well for disnake the method is just same
get_channel is same too 
then whats the prob
I knew god had a punishment for me 
doesn't get printed at all
Ah, how can I use this for that?
!d disnake.PartialMessageable
class disnake.PartialMessageable```
Represents a partial messageable to aid with working messageable channels when only a channel ID is present.
The only way to construct this class is through [`Client.get_partial_messageable()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.get_partial_messageable "disnake.Client.get_partial_messageable").
Note that this class is trimmed down and has no rich attributes.
New in version 2.0...
hmm
!d discord.Interaction you get this class as an argument in the event
first you'll check the type of interaction so that its select type
next you will check if the select was one made for your select roles
then you can get the label of interaction using interaction.values and convert it into a role using discord.utils.get(interaction.guild.roles, name= the name)
and finally add the role
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
!d disnake.Client.get_partial_messageable
get_partial_messageable(id, *, type=None)```
Returns a partial messageable with the given channel ID.
This is useful if you have a channel\_id but donโt want to do an API call to send messages to it.
New in version 2.0.
@outer flint ig try
wait no
that doesnt make any sense ๐
!d disnake.Client.get_message
get_message(id)```
Gets the message with the given ID from the botโs message cache.
LoL
use that
for that u dont need to get channel
bot.get_message(id)
the for reaction in message.reactions 
so just message = bot.get_message(message_id) ?
why isn't it returning what I want
yep
do print(string.upper) ig xd
idk lol
uhm... it is none 
printing None?
message = bot.get_message(message_id)
print(message)
print("message ok")
users = set()
print("users created")
for reaction in message.reactions:
print("reaction")
async for user in reaction.users():
# if user.role != "Player":
users.add(user)
await ctx.send(users)
yeah, even with new message id same None
It's an object it's not suppose to return anything
how do i make my bot also check for another message
Guys why i getting error
no module named 'cogs'
This is my code
import discord
from discord.ext import commands
import os
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or(">"),intents=discord.Intents.all())
async def setup_hook(self):
print("i am ready")
for cog in os.listdir("rustcomp/cogs"):
if cog.endswith(".py") and cog.startswith("_"):
try:
load = cog.replace(".py","")
load = f"cogs.{load}"
await bot.load_extension(load)
except Exception as e:
print(e)
bot = botclass()
You have to give it a valid path to the cog
I am not able to understand what path to give it
What does your project structure look like
My code is in init.py
rustcomp-|
bot-|
__init__.py
cogs-|
rust_compiler.py
try:
.... await client.wait_for(..., timeout=seconds to wait)
except asyncio.TimeoutException:
.... x
where do i add the code above @naive briar
Uhhhhhhh
I really don't know about that
Hmmm?
What/who?
try message.content
!d wait_for
No documentation found for the requested symbol.
!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**...
The get_message is an object so it's suppose to return none, you must do message.content
๐ what...
What the
?
fire
get_messageis an object- objects are basically class instances of None
- message = None and None has an attribute
content
๐ everyday godly advice
cog.startswith
but rust_compiler doesnt even star with _
Sorry my explaining is very shitty
My brain dies sometimes
๐
๐ค
i want my bot to wait for 2 things
huh
at the same time
ok
Did you put double quotes around it
xd
first u have to wait for 1 message then for another
I don't understand anything that happens here rn
same

get_message is a method of the Client class
i have my bot waiting for a user to send a id however i also want my bot to wait for a user to send a message containing "#"
which returns a Message instance
sup
What?





