#discord-bots
1 messages · Page 1153 of 1
me for no reason
I would recommend starting with a simpler project... especially if you're planning to meddle with voice
skill issue keyboard
imagine
can someone tell me where i find terminal
depends on ur os
where do you edit the code
im using replit
inb4 replit
go to shell lmao
NOOO LATENCY
if you dont see that option you're probably too ignorant
i was not fast enough 😔
skill issue
replit, yes the service which gets its cpu and memory 100% consumed just by poetry update
i found a folder thats named pip and it has a file thats named pip.conf
you don't know how fast I made this replit account
it couldn't compile a 3 liner cpp file, its terrible
somebody needs to make a meme regarding the very common and stereotypical case of python newbie following a swas.py/lucas/carberra tutorial and gluing random code from across the internet in an attempt to become a "professional bot developer"
ikr, just get github students plan use codespaces
@novel prairie
bruv
or just go get a VPS and ssh into it
best type of (video)content on programming is just talks, like pycon, they give you the most info
ye and i paste it there?
yeah pip install discord.py[voice]
something that replit can never be
did you hardcode that
I don't know what that is
pip discord.py[voice]
ERROR: unknown command "discord.py[voice]"
pip install discord.py[voice]
it's blue, so what
its more advanced* 
iwr -useb get.scoop.sh | iex
scoop install neofetch
scoop install git # if no git installed
it says this is this right?
nstalling collected packages: PyNaCl
Successfully installed PyNaCl-1.4.0
yes
ok
that's good
its ur setup, get the windows terminal thing from ms store or something
can i create a command that says !leave and when im doing this command the bot leaves the vc?
!d discord.VoiceClient.disconnect
await disconnect(*, force=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Disconnects this voice client from voice.
@novel prairie ^ you can get the voiceclient through ctx.voice_client or guild.voice_client
can you sent me an example on how to do that?
do what
@bot.command()
async def play(self , ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for a song, this may take a few seconds...")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I couldn't find the song you asked for. Try using my search command to find the song you want.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"Song added to the queue at position {queue_len+1}")
else:
return await ctx.send("Maximum queue limit has been reached, please wait for the current song to end to add more songs to the queue")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
this is the command for the play
and it doesnt work
how can i fix it?
!ytdl moment
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)
😄
yea
i thought you used kali
oh lol
codespace is for paid users right?
thats github codespaces and yes online vsc
free for students
ah k
most of the code available online rn are outdated
sarth
what was i supposed to do here again
i dont see the codespace thingy in repo? how do you access it
python -m pip install -U git+https://github.com/Rapptz/discord-ext-menus?
https://github.com/codespaces would be fastest way to access
or, open your repo,
press . on the keyboard
it will open a normal vsc editor
you can open it in codespace from there
ya i mean i dont see this codespace tab
you got github students plan?
mhm
yes i think ...
i have mine but it's against tos
u should how else did u get pycharm prof
make sure you're logged in with that ID
unless u paid
for it
i am
thats weird can i see a ss
what about creating from the link, does that work?
these methods
how can i fix this
?
yea wait
@bot.command()
async def kick(ctx, user: discord.Member, *, reason=None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
await member.kick(reason=reason)
await ctx.send(f'User {user.mention} has kicked.')
Guys how can we check that a user have mentioned someone in the message?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
aight i missed those, ill try that
File "main.py", line 257
await user.kick(reason=reason)
^
IndentationError: unindent does not match any outer indentation level
Can you give me one example
@bot.command()
async def kick(ctx, user: discord.Member, *, reason=None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
await user.kick(reason=reason)
await ctx.send(f'User {user.mention} has kicked.')
Remove 1 space
what is your listener event function ?
oh nvm i fixed it
your on_message function
um
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
Can you give me one example?
sorry wrong ping
i fixed it but it doesnt work for bots
like if i want to kick a bot it doesnt work
yes
it says this
discord.ext.commands.errors.MemberNotFound: Member "<@&998564457317928994>" not found.
no im mentioning the bot
is there any way to make the bot stop responding to the commands?
stop them
no replies at all
the bot is online but does not reply completely
yeah I already do
but I want it to stop replying on a certain status
like
if it's dnd it'll not reply
yes
bot.on_message= lambda m: ...
``` add this whenever you want that to happen
@slate swan
how do you set the dnd status
it's a cog
one day I'm going to calculate how many electrons this guy wastes with typing self.bot.user.id instead of the bot's actual id in his code
sniff
I'd prefer doing that too tbh
you're setting it to IDLE here tho, do you edit it to DND later?
helpful while testing or if you open source the project
@slate swan
Can you give me example of the mentioned thing?
ping one more person randomly ask them
me
Bruh he was telling me before some time and i got offline so i asking now
if message.mentions:
that person just pinged someone bro
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
you can do this ```py
bot = commands.Bot(...)
@bot.event
async def on_message(m: discord.Message) -> None:
if m.guild.me.status == discord.Status.dnd:
return
await bot.process_commands(m)
if member.mentioned_in(message):
member was pinged in that message omg
How will I get id of mentioned user?
I need it for my afk comamnd
wasted electrons
this is true for role mentions too btw
Is it correct?
@bot.event
async def on_message(message):
if member.mentioned_in(message):
id = message.mentions[0].id
you wasted sum electrons by writing electrons instead of e-, thanks
damnit
member is not defined
Hmmm
you should use this one
Memebe = message.author?
e = b
Idk how to
its the same, but .event replaced with .listen()
@bot.listen("on_message")
async def my_uwu_on_message(message: discord.Message) -> None:
if message.author == client.user or not message.mentions:
return```
Whats this the image
okay this works, but is processing messages needed? cuz I already had to remove it in another listener because of it making the bot sending double messages
why am I hallucinating
Who's this guy
its not
you need it there else the commands wont work at all
ur in a cog so u dont needa process it
it’ll double the message
its an event, not a listener
please dont misguide them
aight
<@&831776746206265384> some person is posting random pictures in the channel 
that human -> @echo latch
proof
I put it in a cog listener
@echo latch please respect channel topics and avoid spamming channels. Thanks
swear down putting it in a cog will double the message @wispy sequoia
😋
!mute 749274869824487465 Ignoring staff instructions
:incoming_envelope: :ok_hand: applied mute to @echo latch until <t:1658152140:f> (59 minutes and 59 seconds).
how can i fix this?
yeah I removed the process commands
Ye
@bot.listen("on_message")
async def ping(message):
member = message.author
if member.mentioned_in(message):
id = message.mentions[0].id
Correct now?
...
um how can i fix this
.
it wont work at all then. needs to be an event
oh really?
yes, im basically overriding the processing of commands by doing that 😄
which can be done only with events
thx then, it works
async def on_message(message)
member = #ur member
if member.mentioned_in(message):
print("pomg")
@robust fulcrum
Ty
can someone help me with this
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
:)
i recommend not using that, since it will be true if a role was pinged too
Then check with message.mentions
then check the id
well I think processing commands is useless anyways as it'll not respond 😂 but thx anyways
yes thats the best way
the thing is , commands are getting processed only when the status is not DND
I didn't know that
now you do 😛
oh yes, the indentation
Ye thanks :D
Ash is writing an essay 

Yeah on indents prob
expected, totally expected.
I'm not so free lol
No I have a check in it
well then test it and see.
oh, free to talk here?
absulyely not
id' just ```py
if bot.user in message.mentions:
message.reply("touch grass")
absolutely
Ok
message.author.kick 
💀
Perrespective api bad
message.channel.delete()
how so
message.guild.delete() 
discord.delete()
exit()

exit is useless most of the times, sys.exit better
sarthak is that your girlfriend on your pfp 
what makes you think that, and no
your uwuness 
😆
sparky jealous
i got the image on pinterest
absolutely not

anime pfps are boring so
see my pfp
#NoAnimePfpGang
ew
be ready to get cancelled
where the await at 
it's someone's
Lmao
I guess it's time to move on from anime pfps
😔
Coro
bot.add_listener("on_message" , lambda m: m.reply("touch grass") if bot.user in m.mentions else asyncio.sleep(0))
no await needed
ew who likes that
Ash u were busy
and also, as I've been looking to something like this, how do I prevent it from replying if I have command_prefix=commands.when_mentioned_or(PREFIX)

Pillow
api
you can check if bot.user.mention in await bot.get_prefix(messafe)
messafe
cool down
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
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.
Hey hello, i need help with this .py script which utilizes the nextcord lib
from nextcord.ext import commands
bot = commands.Bot(command_prefix = '!')
@bot.command(name="hi")
async def SendMessage(ctx):
await ctx.send('Hello!')
@bot.event
async def on_ready():
print(f'\n\nSuccessfully logged in as: {bot.user.name} - {bot.user.id}')
if __name__ == '__main__':
bot.run("TOKEN")```
i am not getting any errors but the command jus wont work, and yes the TOKEN in bot.run("TOKEN") is replaced to the bot's token. I also trued the help channels but redirected me here
Nextcord
user based
@commands.cooldown(1, 90, commands.BucketType.user)
1 is the times the command can get used before the cooldown
90 is the seconds of cooldown
👍
2.0
@slate swan this is the same exact thing I gave you
Lol
description is optional
because what you are doing is running an infinite loop which blocks the rest of your code
Not making a message spammer would be a good fix

brad 
Yo
I even wrote down some non-blocking loop in this channel, needa check
why it isn't working, i installed this
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Please respect other server members.
Poor Ashley :(
Ur using the right python version?
3.10.1
I had trouble with a module cuz it was installed but for a diff python version
😂
you too :D
And ur code is in 3.10.1?
Ashley be nice to beginners
@bot.command()
@commands.is_owner()
@commands.has_permissions(ban_users = True)
async def ban(ctx, user : discord.Member=None, *, reason = None):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is banned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
await user.ban(reason = reason)
Version 7.5.0 of praw is outdated. Version 7.6.0 was released Tuesday May 10, 2022.
Traceback (most recent call last):
File "main.py", line 260, in <module>
@commands.has_permissions(ban_users = True)
File "/home/runner/zrl-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1779, in has_permissions
raise TypeError('Invalid permission(s): %s' % (', '.join(invalid)))
TypeError: Invalid permission(s): ban_users
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.
ban_members
how can i fix this
Ye permission is invalid
Do what Ashley said and replace the ban_users
Try restarting vscode
can someone sent the code fixed?
We don't spoonfeed
the same problem
That permission doesn’t exist

breh
NITRO Flex
Okie try running ur code with
py -3.10.1 main.py
It’s a library
!pip humanfriendly
good night 
you have multiple versions of py installed then
i recommend using the version flags along with the py command
Ye
Wait do what I said above
dont use pip directly.
Gn, I hope u don't get anime nightmares
its directing to your 3.9
Ye
yes.
ash is pretty much of nightmare herself
Very true
Hrm
Like ur pfp girl is running to hunt down
python3.10 / py3.10
Ye
Strixx remove the .1
And run
If it still says library not found then u need to install for correct python version
okay.
Okie strixx do
py -3.10 -m pip install humanfriendly
||ig sarth is scamming ppl by girl pfp||
Jk
Now no ot thanks
yeah work look at this now:
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
"New in 2.0"
You are using old version
how to upgrade
pip install git+https://github.com/Rapptz/discord.py
For this u need git installed
@bot.command()
@commands.is_owner()
@commands.has_permissions(administrator = True)
async def unban(ctx, user : discord.Member=None, *, member ):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is unbanned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
discord.ext.commands.errors.MemberNotFound: Member "@velvet loom" not found.
how do i fix this
No need for that
u already have a member object just do user.unban()
but you're never going to have a member object when unbanning
if theyre banned they're not a member
it doesnt work because with the Member typehint the library searches for a member and doesn't find one
instead you'll want to use User
where do i change the member?
@vocal plover
user : discord.Member=None
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
show code
@bot.command()
@commands.is_owner()
@commands.has_permissions(administrator = True)
async def unban(ctx, user : discord.User=None, *, member ):
if user is None:
return await ctx.message.reply("You have to mention a user to do this!")
embed=discord.Embed (description=f"User {user.mention} is unbanned", color=discord.Color.red())
message = await ctx.message.reply(embed=embed)
banned_users = await ctx.guild.bans()
user_name, user_discriminator = user.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (user_name, user_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
wdym?
you shouldn't be using that method for unbanning
Is your unban command looking like this?
for ban_entry in banned_users:
user = ban_entry.banned_users
if (user.name, user.discriminator) == (member_name, member_discriminator):
...
Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:
# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))
# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None):
This is dpy 2.0 right?
its replit lol
nice.
Okie
Ye u can use id rather than loop through bans to find the user
Use what sarth did
bruh
i removed the unban command
and now it something like your ip: and idk df goin on
lmao
it wont let me run the program
replit moment. you have been ratelimited.
type kill 1 in the shell and rerun the code.
i need help my discord.py bot is not responding my command. what should i do =((((
show code
Guys why we should not host bot at heroku?
check pins in #965291480992321536
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
this gives no idea of what the issue can be, the piece of code you provided is correct.
Where should we host then?
Any free thing owo
import random
import time
from discord import Game
from discord.ext.commands import Bot
BOT_PREFIX = "."
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
client = Bot(command_prefix=BOT_PREFIX)
@client.command(pass_context=True)
async def ping(context):
await client.say("🏓Pong!")
@client.command(pass_context=True)
async def pong(context):
await client.say("🏓Ping!")
@client.command(name="8ball",
description="Answers a yes/no question.",
brief="Answers questions",
aliases=("eight_ball", "eightball", "8-ball"),
pass_context=True)
async def eight_ball(context):
possible_responses = [
"Sure, why not",
"Probably not",
"For sure",
"Never in a million years",
"The chances are pretty high",
]
await client.say(random.choice(possible_responses) + ", " + context.message.author.mention)
sry for my delay
Any free thing owo
yes
12 months of aws for free
(basic)
or oracle's 
or subscribe to the github student developer pack, youll get a year's subscription for digital ocean
???? using rapptz git thing
Don't they require CC?
yes
this is just some default logging added in 2.0^
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=...)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
my slash commands aren't showing up, thought they were related
you can set the log_handler to None to remote it easy
any ideas? ive enabled application.commands during invitation
are you syncing the commands?
can i make help command categories manually using command names?
hm, maybe wait for some time
alright
any alternative? or should i just remove it as a whole
the indentation level
the on_ready functionis inside the init function
ahh
nvm
no you're right
setup_hook
lemme self advertise my gist
gib me a minute
yeah it works lol
no you got it. faulty indentation level
now i have a few other questions related to this
that too but you shouldnt sync in on_ready, use a setup_hook or a message command
yeah?
i've made lots of bots in the non-2.0 version so i'm familiar with stuff like create_channel and add_reaction etc.
are they any different in this version?
this is my first time on the new discord.py version so i'm not too sure
no
okay perfect. appreciate your help 🙌
,
will do
so just replace on_ready with setup_hook or is it a whole other block of code?
why @client.command() is not working guy :((((
no
no for?
well you do it like this (same) but on_ready and setup_hook are different
ah
more information on how and when setup_hook works -> https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#fundamentals-for-this-gist
👍
its possible to make a bot take a screenshot of a message?
no
im tryna make it take a screenshot of a discord server invite
i thought i saw it done once
If I use PIL screenshot thing and make a ss comandn will it take a screenshot of my screen?
most of the code is outdated, did you copy from some tutorial?
i see this type of stuff on stackoverflow from ppl tryna fix errors or copy code not knowing it was made in 2018
yep, there has been lot of changes in discord.py since then.
https://www.toptal.com/developers/hastebin/fobavohesa.py
When I write !sregler doesn't the bot send anything but It deletes the message
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yes i want to know how it working
So how can i fix it
just use a more recent tutorial
anyone knows how a discord bot could verify the number of members a server has if it takes a server invite as an argument
Would not recommend a Enterprise hosting provider for a Discord bot. I have seen way to many new people run up bills from a few dollar to 100s, because they dont know what they are doing, leaving services they dont need running, etc.
Better off with a RasberryPi or something and just host from that, if you want free.
hm yeah agreed
how do i create a thread with dpy2?
I'm unable to send price data
ERROR: [1/1] Webhook status code 400: {"embeds": ["0"]}
i tried different datatypes: str, float, int none of them works. When i hard code input the price it is working.
In my dict it looks like this: 'price': 169.99,
Using this piece of code:
embed.add_embed_field(name="price", value=item['price'])
Any ideas what im doing wrong?
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
discord.guild is a module and must exist, they havent installed discord.py properly mb
discord.guild is a module? 
oh a file
skill issue
Lol
Ye ikr
why would they document a .py file
Hi, excuse me for disturbing you. I'm new and I would like to know if someone could teach me or inform me on the bases of the code of a discord bot.
I use Visual Studio Code
guys i need help , 1) py @client.tree.command(description="Unban a username") @app_commands.checks.has_permissions(ban_members = True) async def unban(inter: discord.Interaction, id: discord.User): try: await inter.response.send_message(f"{id.name} has been unbanned") except: await inter.reply(f"The user you are trying to unban is not banned") finally: await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id)) i need this cmd to be multi guild, 2) it doesnt unban the user but says it did
Put the unban inside the try
how to create a thread with dpy 2.0?
kk
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.
New in version 2.0.
thanks
@hybrid fjord
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
try:
await inter.response.send_message(f"{id.name} has been unbanned")
await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id))
except:
await inter.reply(f"The user you are trying to unban is not banned")``` like this/ also will it work for multi guild
Remove the message send from the try except block and add an else after it and put the confirm message there
You could make it ephemeral
discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: NameError: name 'create_thread' is not defined
Show code
oh hold on
discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: HTTPException: 400 Bad Request (error code: 20035): Guild premium subscription level too low
i know what the error means, but what's the lowest auto-archive without boost
Not sure
wdym?
discord.app_commands.errors.CommandInvokeError: Command 'ask' raised an exception: HTTPException: 400 Bad Request (error code: 20035): Guild premium subscription level too low
says 24h is too low, but i can make a 24h thread in the same guild??
ah, u cant create a thread w/o a message without boost
try:
await guild.unban(...)
except discord.HTTPException:
await send('failed')
else:
await send('success')
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
try:
await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=id))
except discord.HTTPException:
await inter.response.send_message('Unbanning Failed')
else:
await inter.response.send_message('Unbanning Has been Successful')``` like this?
yeah
actually the unban part wont work. You should rename the id parameter to user in my opinion but its best to put the user object straight into unban
My discord bot is sending 2 embed messages. Here is the code (Im working on it) @client.command() async def embed(ctx): embed=discord.Embed(title="Embed Message", description="Test Message", color=discord.Color.blue()) await ctx.send(embed=embed)
Wdym?
Idk I think with the id it’s Easier
alright but pass id straight onto unban
oh
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, user: discord.User):
try:
await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=user))
except discord.HTTPException:
await inter.response.send_message('Unbanning Failed')
else:
await inter.response.send_message('Unbanning Has been Successful')``` will this work?
no the name of the parameter was an optional change but your unban needs to look like this
await inter.guild.unban(<user_object_here>)
can u help me fix it? cuz i have this: await inter.guild.unban(discord.utils.get(await inter.guild.bans(), id=user))
await inter.guild.unban(user)
will this work for multiguild btw?
yeah
ok]
wait wdym by multiguild
im making a public bot, it will work in any server the command is ran in
yeah ok
why it isn't work?
it doesnt work now, because if its user: then it wont work, the user isnt in the server so i cant mention it
hello
has to be done through id
how i can download discord.py 2.0.0 to pycharm
install 2.0
well the name of the parameter doesnt matter
how i can install 2.0
kk
you can name it whatever you want
how
how i can download discord.py 2.0.0 to pycharm :\
ok
@slate swan pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
:/
wat to do @slate swan
you need to fix your pip
or install python xD
how to fix pip
try python -m pip install....
python -m pip install....
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
with those ......... ?
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
embed = discord.Embed(
title="TelSpin Role Error",
description=f"you have alredy the role",
colour=0xF42222,
)
await ctx.send(embed=embed)
else:
raise error
not get anything if my meber as alredy the role
it invokes pip as a module
because im pretty sure that exception isnt the right one
it have a eror with python -m pip install your_package
python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
- python -m pip install https://github.com/Rapptz/discord.py
-
+ CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
You need to install python
try, py
Or that
use the name py over python
Sorry I just never used python on a windows machine
if you have python installed you might need to add it to your path
ok
wym
Collecting https://github.com/Rapptz/discord.py
Downloading https://github.com/Rapptz/discord.py
/ 207.1 kB 342.9 kB/s 0:00:00
ERROR: Cannot unpack file C:\Users\Copy Service\AppData\Local\Temp\pip-unpack-iylvvlmk\discord.py (downloaded from C:\Users\Copy Service\AppData\Local\Temp\pip-r
eq-build-iybwcn23, content-type: text/html; charset=utf-8); cannot detect archive format
ERROR: Cannot determine archive format of C:\Users\Copy Service\AppData\Local\Temp\pip-req-build-iybwcn23
WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available.
You should consider upgrading via the 'C:\Users\Copy Service\AppData\Local\Programs\Python\Python310\python.exe -m pip install --upgrade pip' command.
PS C:\Users\Copy Service\PycharmProjects\bot>
```Done?
what am I installingtho
@slate swan
@slate swan :/
seems to me like it had an error
Were can i find someone who codes in json to help w holding data for my discord bot??
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
embed = discord.Embed(
title="TelSpin Role Error",
description=f"you have alredy the role",
colour=0xF42222,
)
await ctx.send(embed=embed)
else:
raise error
not get anything if my meber as alredy the role
That job is suited for an actual database
Yeah😶 i just dont code in json other wise id be fine
Also what do you mean by “code in JSON”? JSON isn’t a language
whats wrong with it 😫
pip install -U git+https://github.com/Rapptz/discord.py
⏫
i will try 🥲
It says invalid requirement :C which I dont know what its specifically referring to but it did run so I thank you for that 😅
How its saying self has no load extension method
even tho self is the bot?
Swap discord.Client to commands.Bot
ty <3
that's a change presence on_ready
not good?
You can set the activity when connecting to webhook iirc
!d discord.ext.commands.Bot constructor kwarg
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.
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
Basically: don't 👏 do 👏 shit 👏 in 👏 on_ready.
class aclient(commands.Bot(
activity=discord.Activity(
type=discord.ActivityType.watching,
name="the Nebula Network"))):
tada
Any other improvements to make?
You can't inherit from an object
Can't make improvement to what won't work
You need to parse these parameters to superclass init
he said I could put it in commands.Bot so idk what you mean?
I mean OOP class inheritance
You can inherit from a class which is commands.Bot, not from an actual instance of that class, you init super class with super().__init__(...)
Not to recommend you should, but with the way classes work you can make it sorta inherit an object
Class inherits from object ik that but let's not dive into useless for this case stuff
For this case he should not inherit from an instance
!e ```py
class A:
def init(self, *meta: tuple[str, tuple[type, ...], dict[str, "Any"]]):
...
class B(A()):
...
@pliant gulch :warning: Your eval job has completed with return code 0.
[No output]
Idk if dpy 2.0 supports enum typehinting but I think that should do the thing
Is what youre trying to get me to do?
I dont think so
Ok I am not into like explaining OOP (I suggest reading about it nevertheless)
class AClient(commands.Bot): # and yeah the naming convention
def __init__(self):
super().__init__(command_prefix=".", intents=discord.Intents.all()) # why'd you even provide application_id```
Idk I just thought you needed the application_id in there lol
class MyBot(commands.Bot):
def __init__(self, ...): # any other optional arguments you want
super().__init__(command_prefix='...', intents=..., ...) # regular bot constructor arguments go here
Awesome, thanks for your work. Could you PR that to python-discord/site and I can review it for you?
Just follow the template that other similar PRs have done (e.g Okimii's, Ashley's)
Ok I think ima figure it out
Feel free to ask me if you have any troubles, I'd be more than happy to get it sorted out
@sick birch I think I did figure it out lol https://github.com/python-discord/site/pull/746
All checks failed ig I've done something wrong tho
I want to make a command that after some time, it would change the message automatically.
Example: .text and it would say "good morning". After a few hours, if I re-executed the command, it would say "good night".
Does anyone have a base for that?
You only have the worry about the first 2 checks. The lint check failed because of trailing whitespaces, which is an easy fix. You just need to lint it locally, then commit & push
Ok
You can get the current time by using datetime.datetime.now() I believe, and change what message is sent depending on that
The example I gave wasn't the best either. Basically the command was for every day to create a different number automatically
but on that day, always be the same
Also @vale wing, the MD file is missing a header, you can find out how to get the proper headers for your file here: https://github.com/python-discord/site/issues/695 (see the Helping with the migration of pin(s) section)
@sick birch ok those 2 checks are successful now
Awesome. The rest are broken for now so don't worry about them. I will review it when I've got time, and thanks again!
Ty
@tasks.loop(seconds=40)
async def changepresence():
global x
guild = client.get_guild(957301746739339307)
game = iter(
[
"Help hâlâ hazır değil 😐",
f"Kasada {data['kasa']['cash']} lira var!",
f"Casino {guild.members} kişi!",
"💸",
f"Sürüm: {version}",
"Özel roller, para ve boost almak için !Bağış yazabilirsin.",
]
)
for x in range(random.randint(1, 6)):
x = next(game)
await bot.change_presence(activity=discord.Game(name=x))```
can somebody help me please?
its not working
hello how to ping users with bot
i mean to use command like !ping <user>
and bot will ping him 10times
why are you sub-sub-subclassing a Client?
sub sub sub classing?
but how to mention someone
yeah~
commands.Bot is a subclass of discord.Client (sub-
you construct a new Bot using commands.Bot (sub-
and the subclass it again as aclient (subclassing
which could have done easily with methods you were just told
oh Im not using discord.Client but I didnt know that ty
from email.mime import application
from wsgiref.util import application_uri
import discord
from discord.ext import commands
from discord import app_commands
class aclient(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.',
intents=discord.Intents.all(),
activity=discord.Activity(
type=discord.ActivityType.watching,
name="Testing Functionality"))
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await self.tree.sync()
self.synced = True
print(f'{self.user} has initialized.')
async def setup_hook(self):
print('Setup_hook fired')
self.initial_extensions = [
'cogs.core',
'cogs.suggestion',
'cogs.invite',
'cogs.group',
'cogs.ping',]
for ext in self.initial_extensions:
await self.load_extension(ext)
print(f'{ext} loaded')
client = aclient()
#bot.run(os.environ["DISCORD_TOKEN"])
tree = app_commands.CommandTree(client)
Is what is have rn if u want to nitpick it so I can try figuring some of this stuff out because to me it looks normal but to everyone else theyre like wtf 😂
I think there's really no point to the whole self.synced part, and you can just remove your on_ready altogether and sync inside the setup_hook
this is actually normal
client = aclient()
#bot.run(os.environ["DISCORD_TOKEN"])
tree = app_commands.CommandTree(client)
``` and this is not needed, `discord.ext.commands.Bot` already has a tree linked to it
And you can also define your tree inside your class's constructor, so you can access tree where you can access client using client.tree
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
thank u for the suggestions!
so i have a command that doesn't work unless its in a specific channel that has a 1m cooldown. can i make it so if they are in the wrong channel it doesn't trigger cooldown?
you can use a dynamic cooldown
def cooldown_for_channel(message):
if message.channel.id != 28482304823048:
return None
return commands.Cooldown(1,1)
@commands.dynamic_cooldown(cooldown_for_channel)
@bot.command()
async def cmd(ctx):
await ctx.send("test")
do dynamic cooldowns work with slash commands? i tried it before but i dont think i did it right
does anyone know why my code isnt working? Im trying to make it say "Goodbye (mention person who sent the command)" @bot.command() async def goodbye(ctx): await ctx.reply("Goodbye {message.author.mention} 👋!")
they do in dpy but not pycord
ctx. author.mention
ah i'll try it it out
it didnt seem to work. here is the new code: @bot.command() async def goodbye(ctx): await ctx.reply("Goodbye {ctx.author.mention} 👋!")
define 'not work' what's the issue
well when i run my goodbye command it says "Goodbye {ctx.author.mention}"
You forgot the f before the string
Ah it worked! Thank you so much
lol
Like this?
self.tree.sync()
Well I didnt reply to the right thing but would this working for syncing commands
since that message isnt really good context
@client.command() still working?
Do you need to include the guild id or something for slash commands to work?
This is embarrassing to ask but
@bot.command()
async def testing(ctx):
embed = disnake.Embed(
title="Learning Embeds",
description="Testing description"
)
await ctx.send(embed=embed)
It doesn't respond when I type !testing.
I've enabled intents from the Developer Portal
Plus I already wrote this piece of code
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
And I already imported intents
Oh wait.. There's this that shows up. I mean, I've enabled all intents from the portal yet this just won't go away
You need to enable message_content intents in the code too
How do i do that?
Intents.message_content = True
??
Like this?
It says 'Intents' object has bo attribute
Oh. Wait nvm
Got it! Thx!!
Can u give me example? Iam noob
no no I was asking for myself bc Idk either 😂
You can both include a guild ID or not for registering slash commands. When ID Is omitted a global slash command which is available for all guilds the bot is in gets made(Takes some time to register), when registering with an ID it will be for those guild(s) only (They almost register instantly)
Are there common reasons for why slash commands don't register?
Because my cogs are loading and everything appears to be running, I get no errors but whenever I try to start the command nothing shows up, like the bot doesn't appear in the list of options for slash commands
here
Yes, one reason would be not inviting the bot to that guild with applications.commands scope
applications.commands and bot are the only 2 you should need right
Hey so I was building a discord bot for a community i am a part of and i recently heard that slash commands are being made compulsory for all bots.. Is it going to be easier to continue with discord.py and develop /commands or is it better to switch to hikari?
Do u know how to make client.command() work?
discord.py supports slash commands
Off the bat, yea
but which is easier to implement.. hikari or .py
Never worked with Hikari, some of the other folks here have so you'd have to ask them
I see.. thanks
What else would you use bc when I click anything else it doesnt give a URL
maybe?
Thats it
Ill reinvite just in case
Can u give me example
If you can't make a URL just use this https://discord.com/api/oauth2/authorize?client_id=(YOUR BOT ID)&permissions=0&scope=bot%20applications.commands
Still not working unfortunately
says its online but doesnt show up in the list
are you syncing properly after changing/adding or removing any commands? (assuming you're using discord.py 2.0.0a)
though in any of the forks you need to sync as well i think
@stiff fern
well it's not a good idea at all to auto sync, most people have commands to sync everything when it's needed
and i think you should be doing self.bot.tree.sync()
What should i input here if I want the bot to place the user's avatar as the thumbnail?
embed.set_thumbnail(url=???)
I tried putting
{member.avatar_url} but it didn't work
here's a sync command (for discord.py) that a lot of people use, you can also use jishaku sync to sync commands if you know what that is
what version of discord.py or what library are you using, you may need to be using member.avatar.url instead
that’s what I have?
okay ty
Oh I thought self = command.bot
I see you did self.bot I just did self
i'd suggest reading up on what self does, say you have self.bot = bot in your class, you'd have to use self.bot to get the bot object
disnake
Let me try that
same with any other variable, self.process = psutil.Process(os.getpid()), you'd have to get self.process to be able to access your variable in the class
i dont know disnake very well, but i think that should work from what the docs say
https://docs.disnake.dev/en/latest/
Alright, will read thst. Thx!
Np goodluck
#The codes preceding this one showed no errors regarding indentation.
url="https://discord.com/channels/943462265317912576/953113946930438185/"
)
embed.set_thumbnail(url="{member.avatar.url}")
await ctx.send(embed=embed)
Help. I couldn't figure it out myself. It said:
indentation error. Unindent doesn't match any outer indentation level
are you familiar with how indentation works
More or less
I'm still fairly new so I'm still not very experienced with it.
it should just be
url="etc etc"
embed=whatever
await ctx.....```
instead of
```py
url="etc"
embed=
await```
Wait let me try
When that type of error is returned it could also mean that both spaces and tabs are being used unnecessarily on some lines, right?
yes
Let me try rechecking the whole code first
you can't mix n match tabs/spaces
repl can also cause indentation issues randomly sometimes if you're using that
Yeah. I'll probably be fixing it later lol. Gtg. Seems like it's only indentations that's the problem
I'll just double check everything
Thx for the help
Wait. Seems like I fixed it... But now another problem is that the repl is loading forever.
Whelp, I'll figure it out later
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
The source code?
GitHub might be a better place to read it honestly
i also want to know where is saved
in my pc
pip install thing ?
That’s very dependent on your python installation location, and any activated virtual environments
I believe there’s a pip command to show you where the package is located, but personally I don’t use pip
which installation process u use sir
git hub add ?
Poetry mostly
We use it for most of our projects here at pydis, so I kind of just got used to that and use poetry now lol
- poetry is very cool
how does bot replies in a specific server? because I have a problem with this. For example I have a Server 1 and Server 2
if I send command to Server 1 the bot replies in Server 2.
Can someone explain me?
You’re probably not using the context of a command properly
We’d need to look at your code to be sure though
is discord.utils.get recommended here?
I haven't coded it yet, but I will try right now
import okkk
okkk.okk()
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
client = MyClient()
client.run('xxx')```
import random
import asyncio
class okk(discord.Client):
async def on_message(self, message):
if message.content.startswith('guess'):
await message.channel.send('Guess a number between 1 and 10.')
def is_correct(m):
return m.author == message.author and m.content.isdigit()
answer = random.randint(1, 10)
try:
guess = await self.wait_for('message', check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))
if int(guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send('Oops. It is actually {}.'.format(answer))```
file one and 2 is it ok ?
@dry crown😳
do you want 2 bots in 1 script?
no no i want 2 script runs when i run 1st to login bot
i want guess command works .. file 2 line 7
what error is given
from okkk import okk
hmmm not working
oh I see the problem
what ?
hmm hmm u can , waiting
ok ok wait
File 1
import discord
from okkk import okk
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
self.okk = okk(self)
async def on_message(self, message):
await self.okk.__receive_message__(message)
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
File 2
import discord
import random
import asyncio
class okk(discord.Client):
def __init__(self, client):
self.client = client
async def __receive_message__(self, message):
if message.content.startswith('guess'):
await message.channel.send('Guess a number between 1 and 10.')
def is_correct(m):
return m.author == message.author and m.content.isdigit()
answer = random.randint(1, 10)
try:
guess = await self.wait_for('message', check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))
if int(guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send('Oops. It is actually {}.'.format(answer))
@limber bison
hmmmm
unindent does not match any outer indentation level (okkk.py, line 9)
File "C:\Users\Kamal kishore\Desktop\S3X\main.py", line 2, in <module>
from okkk import okk```
fix the indentations
yes but the problem is the indentation
and how to fix that
align to the white line
ohh got it
thanks @dry crown
@dry crown working , what mistake i am doing ? 🥲
from import ?
is one right
is it working
your mistake is
the okk.okk() will not update everytime you message
discord.utils.get I guess
URBAN API necessary?
Can I get economy bot git so I can read it
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
Replit: Updating package configuration
--> python3 -m poetry add aiohttp discord get
Ignoring invalid distribution -iohttp (/home/runner/Darknix-Security-Fixed/venv/lib/python3.8/site-packages)
Using version ^3.8.1 for aiohttp
Using version ^1.7.3 for discord
ValueError
Could not find a matching version of package get
at venv/lib/python3.8/site-packages/poetry/console/commands/init.py:367 in _find_best_version_for_package
363│ )
364│
365│ if not package:
366│ # TODO: find similar
→ 367│ raise ValueError(
368│ "Could not find a matching version of package {}".format(name)
369│ )
370│
371│ return package.pretty_name, selector.find_recommended_require_version(package)
exit status 1
@spin.error
async def spin_error(ctx, error):
if isinstance(error, discord.MissingPermissions):
embed = discord.Embed(
title="TelSpin Role Error",
description=f"you have alredy the role",
colour=0xF42222,
)
await ctx.send(embed=embed)
else:
raise error
not get anything if my meber as alredy the role
it's missing permissions
it tells the member if they don't have the required permissions
.bm
@vale wing any idea?
There's no package named get
I got this error trying to use Discord.py's components
"Value of field "type" must be one of (2, 3, 5, 6, 7, 8)."
view = discord.ui.View()
view.add_item(
discord.ui.TextInput(label='Titolo', style=discord.TextStyle.short)
)
await ctx.send(view=view)
You can add TextInput only to modals
discord.ui.Modal() ?
instead of discord.ui.View(), right?
or do I have to add the modal to a view?
Not sure bot most likely input function causes blocking
can you precisely explain what you're trying to do?
Why even make communication through terminal
You could redirect messages to your DMs for example
And then have sort of reply button
Or even simply reply to a message
You have 2 functions named the same
Also what the hell for do you need asyncio.run() there
why is it using classes?
Lmao
I need a "command" function flow
Because subclassing is the correct way of implementing them
@bot.command()
async def sondaggio(ctx):
modal = discord.ui.Modal(title="Sondaggio")
modal.add_item(
discord.ui.TextInput(label='Titolo', style=discord.TextStyle.short)
)
await ctx.send(view=modal)
like this, but I don't know how to use it
so do I have to create a subclass for each modal?
isn't it expensive?
You could make own "generic" class depending on your needs
ok I got that this is the right way, but why?
but in the example the subclass is not generic, am I wrong?
Like I did with views for example https://github.com/Exenifix/AIAS/blob/801d18bee646503b338ac5ce21cff82b3a703122/utils/views.py#L32-L76
okay
another question about subclassing
do I have to subclass only when talking about components?
Subclassing allows you to not do the same thing every time
or do I have to subclass everything in discord.py?
Subclassing is a tool and can be used whenever you'd like to
Personally I usually subclass commands.Bot
And we all subclass cogs
what is it?
My english is not enough to express how useful subclassing is
mine is not enough to make the right questions lol
@livid hedge just asking do you know about class inheritance
yes
Subclassing is that thing
I think you should be able to figure out when to use it by yourself shouldn't you
Typically as I said: bot, cogs and views/modals
gotta rewrite a lot of code
Gl with that
it's gonna be a nice day
There are some of them more advanced, like CheckFailure when you want to create a custom check
I am currently rewriting a bot that I made with sync sqlite wrapper (why the hell) now it just eats 100% of CPU every 20 seconds and is extremely slow
damn
Please bro my senior asked me to study a database, which is used to schedule things
names of tables and rows are like this XPRTR_CNFG
The what
i mean WTF, why people create databases when they're drunk
X-ray Propeller Retrograde Tyrannosaurus Rex _ Chinese National Flying Gorilla
Lmao
hey can someone help me and say how those „new“ buttons are called under messages which u click and get a message that only you can see?
tyy and what are those new apps that look like bots?
I couldn’t find anything in google when I searched for Apps?
Bots are apps
These are discord integrations
They access some of your discord data to use on their site
You can create app on dev portal not only for bots
oh do you know where I can learn about coding such?
Afaik it uses discord API as well so you can just use their docs
where can I find a "doc" that correctly tells me how to subclass discord API?
You can't subclass API
thx a lot!
i mean everything
Erm
im rewriting everything
Subclassing is a way of extending the functionality of another class
I have to improve my english
yeah I know
but for example I want to subclass the Bot class
What functionality are you going to add to it
I think doing it "manually" isn't the fastest way
for example the commands
I can add them inside or outside
You group commands into cogs
I don't know which is the """cleaner""" way to do it
If you follow the best practice
I think there were some tutorials
yeah but
I followed a tutorial to create bots
and know I just discovered that I have to subclass
I have to search through docs
I think that's the best way to do it
Lol tutorials don't teach you how to code a bot
they teach you how to create a bot, it's pretty different
This has a pretty nice explanation about cogs but for forks, you can find out the principle and then look at the docs because for dpy 2.0 it's a bit different
A tutorial to help you make better Discord bots.
@livid hedge
Also you may check some projects on github like the one I linked to you before
that's what I mean
It's a fork but as I said, you need to understand the principle
ok, ty
Hi! is possible dynamic url link in text?
link_stockx = 'https://stockx.com/es-es/' + item3['urlKey']
embed.add_field(name='StockX', value='StockX')
no link appear in embed
just edit the message/embed
Thank you very much! I tried but I don't know how to do it hehe
msg = await ctx.send(embed=embed)
newembed = discord.Embed()
await msg.edit(embed=newembed)
OOO ty!
hi. pls help
zeffo 
hi. pls help
@classmethod
async def validate(cls, bot: Bot, iact: Interaction):
if iact.guild is None:
raise GuildOnlyException
user = cast(Member, iact.user)
voice_client = cast(Optional[Voice], iact.guild.voice_client)
if (voice := user.voice) and (channel := voice.channel):
if not voice_client:
voice_client = await channel.connect(cls=Voice)
elif channel != voice_client.channel:
if len(voice_client.channel.members) == 1:
await voice_client.move_to(channel)
else:
raise DifferentVoiceException
else:
raise NoVoiceException
return cls(
bot=bot,
guild=iact.guild,
voice_client=voice_client,
user=user,
channel=cast(GuildMessageable, iact.channel),
interaction=iact,
)
``` how i can shorten pls

maybe
voice_client = cast(Optional[Voice], iact.guild.voice_client) or await channel.connect(cls=Voice)

im matching with a friend
