#discord-bots
1 messages · Page 97 of 1
in that case refer to the example in the dpy repo like ashley mentioned. hopefully it's a good starting point
okay thankss
is that okay
thanks
run it and see \™️
turn all on and yh
How are you trying to run the command
no..
It should be run with !hi
oh, i see. not printing the command
YH
awesome tysm guys
are you actually calling the command from discord?
oh, great
tyyy
is it ight if i use the free tier of oracle?
otherwise the cheapest version of vultr/digital ocean
i plan on running 2 bots on whichever vps I use
both bots would prob be used in ab 100 servers each
Bot commands are run with the command_prefix prefix
It's like this for all bot commands
alright
https://github.com/Rapptz/discord.py/blob/master/examples/reaction_roles.py#L29
how is this supposed to work lmao
examples/reaction_roles.py line 29
role_id = self.emoji_to_role[payload.emoji]```
bot commands aren't specifically prefix commands though
i dont use prefixes lol
built different
I don't know what prefix commands are
Enlighten me
🔦
aight, I will try to laugh.
It's all so clear now
crisp.
Ashley
Nova
Dani
Panda
class CreateTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Create Ticket", style=discord.ButtonStyle.green, custom_id="create_ticket:green"
)
async def create_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
interaction.guild.get_role(1010395040385876029): discord.PermissionOverwrite(read_messages=True)
}
channel = await interaction.guild.create_text_channel(f"{interaction.user.name}-ticket",
overwrites=overwrites)
msg = await interaction.response.send_message(f"**__Ticket Created Successfully__** {channel.mention}", ephemeral=True)
embed = discord.Embed(title="Ticket Created", description=f"{interaction.user.mention} Created A Ticket! \n Click The Button Below To Close The Ticket.")
await channel.send(f"{interaction.user.mention} <@&1010395040385876029>", embed=embed, view=TicketSettings())
class TicketSettings(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Close Ticket", style=discord.ButtonStyle.red, custom_id="ticket_settings:red"
)
async def close_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.permissions.manage_messages == False:
return await interaction.response.send_message(content="**You Can't Close The Ticket! Only Staff Can!**", ephemeral=True)
await interaction.response.send_message(content="Ticket Is Being Closed..")
await interaction.channel.delete()
await interaction.user.send(f"Ticket Closed Successfully! By {interaction.user.mention}")
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreateTicket())
self.add_view(TicketSettings())
self.persistent_views_added = True
print("Persisitent views added")
@bot.command()
@commands.has_permissions(manage_channels=True)
async def setup_tickets(ctx: commands.Context):
embed = discord.Embed(title="Create A Ticket!", description="Click The Create Ticket Button Below To Create A Ticket")
await ctx.send(embed=embed, view=CreateTicket())```
😭😭😭
but it does make the ticket?
bruh does anybody here have a dashboard for their bot
set interaction.response.author's read_messages permission to True
i have
i will try
interaction.response.author: discord.PermissionOverwrite(blabla)
interaction.guild.author: discord.PermissionOverwrite(read_messages=True),
ill try thank you
well it's not currently running, it was a hobby project. but i've made one
nice
what features did it have
@cold sonnet
then it's user
you could practically configure everything about the bot
not author
oh okay
I'm used to disnake for some reason
thats nice
okay
there's interaction.user
interaction.user: discord.PermissionOverwrite(read_messages=True),
I think they changed InteractionResponse
ill try
its working
good
Regex for input checking with slash commands when
Hi, when I try to edit an embed containing the image, it gets duplicated as shown in the screenshot. I'm setting image in the embed through file kwarg
emb = discord.Embed(
description=f"{inter.author.mention} is dropping a set of 3 cards!",
color=0x2F3136)
emb.set_image(file=discord.File(buff, filename="image.png"))
and
m.embeds[0].set_footer(text="This drop has expired")
await self.inter.edit_original_message(view=self, embed=m.embeds[0])
disnake ofc

If you were to remove the set_image?
m.embeds[0].set_footer(text="This drop has expired")
m.embeds[0].set_image(file=None)
await self.inter.edit_original_message(view=self, embed=m.embeds[0])
already tried that
Traceback (most recent call last):
File "/home/runner/Bot/views.py", line 45, in on_timeout
m.embeds[0].set_image(file=None)
File "/home/runner/Bot/venv/lib/python3.8/site-packages/disnake/embeds.py", line 462, in set_image
raise TypeError("Neither a url nor a file have been provided")
TypeError: Neither a url nor a file have been provided
url=None?
also tried that
I guess just remove the attachments.
does the region i choose for my oracle server matter?
ik i should pick whats closer to most bot users
but just wondering
there weren't any in the first place
More how close the server is to a Discord server.
interesting, ill look up where discord servers are thanks
hmm 🤔
technical research 
I chose Germany since it's in the middle also close to server and Europa is just more reliable in general.
I mean it makes sense right? The message I sent first goes trough Discord then they dispatch it trough their api.
im not sure b relibility, electricity prices are 4x the usual price
and there might be civil unrest soon bc of living standards
no cap
french government warned there ight be blackouts
even tho we are the ones using nuclear the most
Well not now but since most VPS are contracts before all this it was cheap so people are still paying the same amount. Sucks if you are deciding now to get a VPS tough... 🐒
oracle is free
The french always have civic unrest, I bet they are protesting as we speak.
theres free unlimited tier, they say unlimited
vultr is just 2.50$ tho
Never heard of it.
and theres an offer for 1 pound for a provider in the uk (1 year)
yeah yeah latency 👍
I don't recommend cheaping out on a VPS, 10 bucks a month is fairly reasonable if you look at the specs + electricity cost.
meanwhile me playing on my pc 
My pc draws 230 watt on idle.
why not, vultr has 99.9% uptime
Url?
im planning on using a vps for 2 bots, (serving 100 servers each)
get a rpi 🚶
i have one
run it of ur power bank kek
but since i use the wifi from a neighbour, i cant
i tried using bros trend usb antenna, but doesnt work X0 (the installation driver)
huh?
its kinda a mess to install the driver
so sus wifi from neighbour and whats usb antenna got to do with hosting bot
I actually recently got a new powerbank that could easily handle a pi
powerbank??
noice any power bank is fine as long as it gives steady voltage
rpi was how much voltage 5-12v cap right?
and 1-1.5amp i think
Lemme get the specs
noice 3 outputs two inputs op power bank
2 c types also
how much it cost 👀
4 actually, usb 1/2
pls elp
is that 3 c one each of usb 1 and 2?
2xc / 2xa
105
Euro
damn that 8.5k in inr
I assume that is a lot
button has a callback
hmm lets say that at 30k u can get 8gb ram laptop or u can buy like 3 rpis easily
for 8.5k
i know but how in the callback how can i do different things for different buttons
make different callbacks
But I recently got the steam deck and my phone do be ded sometimes so I wanted something that lasts long, it's also an aluminum chassis.
Yeah sounds about the same pricing as here.
noice noice 😄
but i dont want that, i want it in 1 with an if thing
er it not about the pricing its about indian/asian mindset when shopping 
then use custom id to differentiate between buttons
and how do i use it in an if thing
just use if statement to check with custom ids
what code do i use ?
u can get the custom id using interaction.data["custom_id"]
ok
u could've just asked for code directly why go around the problem
because some ppl make a big deal if i ask for code
fair enough
how do i use it ?
lol
Dw Asher is a known spoon feeder
u don't need to await it
🤷
interaction.data is a dict
do i have to == it ?
yeah
set a custom id then use if == add code below
ok
!d discord.ui.Button if u are wondering how to set custom id
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
ye i knew it but thanku 🙂
👍
it works thanku very much
👍
ok
so i have a question
im writing a bartender discord bot
when i say c!menu the bot gives me the menu
and for example when i say c!water the bot gives me a pic of water
but i want to make the bot delete menu after i said c!water
is it possible ?
possible in weird ways, why don't you use slash commands and ephermal msgs
what do you mean by slash commands how ?
using slash commands, you can send such messages which are only visible to author and can be dismissed anytime
Hello everyone, I have a question who has an example of how to use "wait_for" how to make such a bot that will display a message and wait for the user to respond to it (through the "reply" function). And if a person responds to this message just like that (without the "reply" button), then the bot will ignore him
they are very simple and just like how you make normal commands
Do you need advice on how to do it?
ok how ?
Hi guys! I don't know why this is not unbanning
hm?
which library are you using
something is messed up
what do those underlines say?
weak warnings
im so embarrassed to say but i dont know 0-0
such as spaces blabla
how do i make a command that deletes channels as in the code under the async def stuff
can you send a screenshot or entire statement
💀
am i so stupid
No documentation found for the requested symbol.
!d discord.abc.GuildChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Hello everyone, I have a question who has an example of how to use "wait_for" how to make such a bot that will display a message and wait for the user to respond to it (through the "reply" function). And if a person responds to this message just like that (without the "reply" button), then the bot will ignore him

more like you finished a mechanics book and don't know the value of Gravitational constant
XD
this is not even python
lets not talk about it
I said GuildChannel
Oooo i got it discord.py
why are you extending the code, User object exists
ow ok
you can check this gist - https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
What is this?
you reply to msg, not to member
so i have a question
im writing a bartender discord bot
when i say c!menu the bot gives me the menu
and for example when i say c!water the bot gives me a pic of water
but i want to make the bot delete menu after i said c!water
is it possible ?
i can send the code
I mean, reply to message
you cannot reply a member
?
right
are you using slash command?
Yes
reply is not used in them
Yeah I realised I can use class discord.abc.User
But the code should work anyway
oh. Okey
That's why I'm asking, I want to make a bot that will wait for a response to a message (through the "reply" item). I know what to do through wait_for but I don't understand how. Does anyone have any ideas?
I used that before with ban commands and it completely works
@bot.command() and @commands.command are the same
?
Okay, not the point, how can you use wait_for to request a response through the "wait_for" function
I am not sure (don't remember), I guess it takes a check
"check" is something like a check that checks if the person answered or not?
Lucas unban👀
hello then I have a problem, to make my bot in discord.py, my functions below :
@client.command()
async def rules(ctx):
embed1 = discord.Embed(colour=None, color=0xe74c3c, title='**Réglement du Cinéma** :movie_camera:', type='rich', description='test')
view=Menu()
await ctx.send(embed=embed1, view=view)
displays rules and a button, below, I would like that when the user clicks on accept the bot adds a role to him, but I can't, because I don't know how to give my class the id of the user
the class :
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value=None
@discord.ui.button(label="Accepter le réglement", style=discord.ButtonStyle.green)
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("hello you cliked me !",ephemeral=True)
Hello I want my bot to say that i entered a bigger number than 10
It is possible
Here a example
/play mines:11
Sorry,but our maxim mines is 10
Nah, his version has old ctx.guilds
I might change everything and that's it
It's still his old terrible abstractions
anyone help me please ?
interaction.author
@discord.ui.button(label="Accepter le réglement", style=discord.ButtonStyle.green)
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(interaction.author.id,ephemeral=True)
who has a code example when a person replied to a bot message (using the "reply" function) and the bot answered him this message. And vice versa, if the person did not answer, then the bot can conditionally ignore him
it exits in disnake, I didn't expect a different thing in dpy
it's not in discord.py?
ehm
!d nextcord.ext.commands.Bot.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.command "nextcord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.GroupMixin.add_command "nextcord.ext.commands.GroupMixin.add_command").
hello,
https://paste.pythondiscord.com/ehogafajal <- I have this class
https://paste.pythondiscord.com/unugoyopoz <- And this error, not sure where's the mistake, Help please!, Thanks!
the name of the command should be indicated with a kwarg
@bot.command(name="delete")
and you're missing ctx that is the required positional param for every command
you've defined authorID as self.ctx so you should use it since you don't have self.authorID
every message command*
max_values=1 options=[<SelectOption label='Komi Anime Computer Wallpapers' value='Komi Anime Computer Wallpapers' description=None emoji=<PartialEmoji animated=False name='🚲' id=None> default=False>, <SelectOption label='Shouko Komi Wallpapers' value='Shouko Komi Wallpapers' description=None emoji=<PartialEmoji animated=False name='�'' id=None> default=False>, <SelectOption label='Komichi Akebi Wallpapers' value='Komichi Akebi Wallpapers' description=None emoji=<PartialEmoji animated=False name='🏰' id=None> default=False>, <SelectOption label="Komi Can't Communicate Desktop Wallpapers" value="Komi Can't Communicate Desktop Wallpapers" description=None emoji=<PartialEmoji animated=False name='🚄' id=None> default=False>, <SelectOption label="Komi Can't Communicate Cute Wallpapers" value="Komi Can't Communicate Cute Wallpapers" description=None emoji=<PartialEmoji animated=False name='🎇' id=None> default=False>] disabled=False>
Traceback (most recent call last):
File "C:\Users\Ravi\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "e:\Programming\Rishit\Python\Projects\Pinterest-Bot\main.py", line 60, in callback
await interaction.response.edit_message(embed=self.embed,view=self.view)
File "C:\Users\Ravi\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 812, in edit_message
await adapter.create_interaction_response(
File "C:\Users\Ravi\AppData\Roaming\Python\Python310\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
``` changed the code to what you said, but this error pops up, confused again
Could someone help me to just print the id of the user who clicks the button? i use discord.py
@discord.ui.button(label="Accepter le réglement", style=discord.ButtonStyle.green)
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
print(interaction.client)
interaction.user.id
thanksssss
defer the interaction
non-deferred interaction lasts for 3 seconds
if you defer them they last for 15 min
I saw this on the dpy docs, ```py
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.response.edit(view=self)
```
but I don't actually know how what self.response is? How do I get the interaction?
if i do that, how would i edit my message with the new embed?
i know i can send a followup message but not sure how to edit
the previous
await interaction.response.defer() # at the start of your body function
...
await interaction.edit_original_response(...) # at the end of the function body where no other logic regarding the command should be performed
you're using d.py right?
can someone tell me why this doesnt work
yes
just search the definition in docs??
Did you import commands.ext?
bot = commands.Bot(command_prefix='!', somewhat like this
yes
already did, leme try again tho
@slate swan it's edit_original_response
could just be a bug, will the bot start?
sorry I confused it with disnake
thanks!
nope, now I get this error
ill check the docs now to see whats wrong
what lib are you using
if you're using discordpy it's
from discord.ext import commands
bot = commands.Bot(...)
or
from discord.ext.commands import Bot
bot = Bot(...)
im using from discord.ext import commands
then you should use the first example
how you import things doesn't matter
you just have to know classes, check docs for this e.g discord.ext.commands.Bot if you do from discord.ext import commands it's obvious that you have to do commands.Bot
thanks I will
its just importing namespaces to define them in the global scope
it seems to be taking long to edit message, is there a reason for that?
are you hosting the bot locally?
it could be your network latency
@client.event
async def on_message(message, ctx):
if message.content.count("\n") > 2:
await ctx.send("hi")
is there a problem with this?
im confused
@glad cradle this?
nvm
yes but there's still and error, also it's await channel.delete(...) and channel should be type hinted as nextcord.TextChannel
blockingio can be a leading cause
!d nextcord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions.manage_channels "nextcord.Permissions.manage_channels") permission to use this.
the decorator should be @bot.command(name="delete")
to put it simple it's
@bot.command(name="delete")
async def wipe(ctx, channel: nextcord.TextChannel):
await channel.delete()
Make sure with an alt account. If it's visible from another account, it means ephermal=True just won't hide messages with embeds for other users.
i did that
no
okay
watch your screenshot
what is that?
blocking calls
oh
a very common blocking call among newbies is time.sleep()
this is the error i got with ur code
you're not passing the channel when invoking the command via discord chat
?
😩😩
the only problem i have rn is that if i switch the category, the download button doesn't shows up, https://paste.pythondiscord.com/hivahurala is my code, i think could be because i am removing the download from view, but i can't think of a another way to replace, the download button with the new link, it gets replaced when i click the button, can you help please? Thanks!
you should at least know python before trying to create a bot
it legit wont work 
why you're passing an int to channel ?
channel is a TextChannel object
it doesn't make sense what you're doing
thas the id
it could only be done by someone who doesn't know Python OOP
LOL
I'm reading the code now
Thanks
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
open is a blocking call
i see
like this?
You need to install, import and actually use it. Or you can read it line by line and await asyncio.sleep(0) at the end of each line reading assuming you are already in an asynchronous context
ah.
that's the basic example of aiofiles
async with aiofiles.open('filename', mode='r') as f:
contents = await f.read()
print(contents)
>>> 'My file contents'
really simple to use
yes, made all of them like that
the code is really messy maybe you could take a look to d.py examples
yep, it is, i'll try to format it better after everything works fine
you're redefining already existing buttons
just wanted to fix the download button problem for now and sleep,
you have a view but you're not using it so much
i think i am using it for every button response?
could you tell to me the lines where there's the logic to replace the button, coz it's too messy and I'm from mobile so I'm practically blind
you could use it better, the view class could be a sorta of container for all your components
so i basically, make a download button, add it to the view , then remove it from view after sending the message, doing same for buttons
i tried to do that but got really confused so did it this way
i haven't done much OOP till now
line 104, 163, 143,145 and few more
you mean if you switch category in the select?
121 , 123
would you mind being invited to the test server? so i can directly show you what it is doing?
ok
btw if that's the case it's just coz you're not handling that case in the select callback
yeah, sort of, ig, but not sure how i can get the download button inside the callback
from what I see everything you are doing in the command body function you can do it too in the select class
btw it has a really bad design you should really look into the examples
i will!, thanks
damn bro i thought it was possible to make an alt with oracle, but they ask so much info
Anyone know why im getting this error
[2022-09-30 16:41:14] [ERROR ] discord.ui.view: Ignoring exception in view <Queue timeout=None children=2> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Deny' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\kaelm\PycharmProjects\1019664108519432267\cogs\gatekeeper\core.py", line 70, in queue_deny_button
await interaction.response.send_modal(DenyPunishType(author=author))
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 895, in send_modal
params = interaction_response_params(InteractionResponseType.modal.value, modal.to_dict())
AttributeError: 'DenyPunishType' object has no attribute 'to_dict'```
how do i upgrade to pip 22.2.2
py -m pip install -U pip also not discord bots related question
thank youu!
You alr have it installed
oh
Does your DenyPunishType inherit from Modal
Dont think so
DenyPunishType gets edited in a message then
each option just sends a diff modal
ive got that
its response.send_modal
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
ik
class DenyPunishType(discord.ui.View):
def __init__(self, author):
super().__init__(timeout=60)
self.author = author
options = [
discord.SelectOption(label="Ban", description="Ban the user with your denial reason.", emoji='🔨'),
discord.SelectOption(label="Kick", description="Kick the user with your denial reason.", emoji="🤜"),
discord.SelectOption(label="Message", description="Send the user a Direct Message with your denial reason.", emoji="💬")
]
@discord.ui.select(placeholder="Select punishment type.", options=options ,min_values=1, max_values=1, custom_id="denyPunishTypeSelect")
async def queue_deny_punishtype_select(self, interaction: discord.Interaction, select: discord.ui.Select):
if self.author != interaction.user.id:
await interaction.response.send_message(content="w⚠️ERROR: You cannot use this menu, it is active under another gatekeeper!", ephemeral=True)
queueChannelVar = interaction.guild.get_channel(queueChannel)
dict = await interaction.client.database.verification.find_one({"_id": interaction.message.id})
msg = dict['_id']
msg = await queueChannelVar.fetch_message(msg)
member = await interaction.guild.get_member(dict['user'])
if self.values[0] == "Ban":
await interaction.response.send_modal(DenyPunishBan(msg=msg))
elif self.values[0] == "Kick":
await interaction.response.send_modal(DenyPunishKick(msg=msg))
else:
await interaction.response.send_modal(DenyPunishMessage(msg=msg))
#@on timeout```
The object you parse as modal argument of send_modal must inherit from discord.ui.Modal
Your class inherits from View
wdym
What are you trying to achieve with that code
Button: Deny
On click, edit message to view=DenyPunishType
Then depending on the option selected in DenyPunishType, open a modal
I don't completely know how modals should be implemented in dpy but definitely not like this
You gotta inherit your custom modal class from discord.ui.Modal class
To send it?
Tbh this looks more convenient than disnake's implementation
this took forever to write
There were like NO resources AT ALL
Figuring out how it worked with the horrible docs was a hell of a time
You mean write what exactly
`class Verify(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label="Verify Yourself", style=discord.ButtonStyle.green, emoji="")
async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):`
The implementation of that thing or the example
It’s not a modal issue I think
This is the first time I’m using a view class then @ select
It's purely your class issue
Instead of a view then adding it frkm the view
So its a issue with that select menu view shit
?
how do i make it a reaction riole
I don’t know how tho as it sends the view fine
If you want to send a modal, you use send_modal, if you want to send a view, you use send_message(view=your_view)
Learn Python :3
await interaction.user.add_roles()
This is what I’m doing tho lol
What you are doing is sending instance of discord.ui.View via send_modal
DenyPunishKick is a modal
A forum to be exact
And what is the code of DenyPunishKick?
Shouldn’t matter since it isn’t even getting sent
It’s the same code tho as all my other working models
Other then passing msg arg in
I hate this slowmode
This error happens because you are doing send_modal(DenyPunishType(...)) and that class inherits from discord.ui.View, and that is in your cogs/gatekeeper/core.py file, line 70
async def test(ctx: commands.Context, text: [str] = None) -> None:
if ctx.channel.id == 1025516828774105211:
embed = discord.Embed(title="**FiveM**", description="**__connect __** ",
colour=0x053305).set_thumbnail(url='')
await ctx.send(embed=embed)
else:
await ctx.send(ctx.message.author.mention+' **Commands can only be send in **#commandstest')```
i dont know why but i have no output
If dosnt Inheret it tho
I'm using discordpy, how do I add an emoji to a button?
emoji = “👋 “
oh
it's a separate thing lol
@discord.ui.button(label=":X:", style=discord.ButtonStyle.red) i was doing this xD
;D
please
@discord.ui.button(label="Yes", style=discord.ButtonStyle.green, emoji=":ballot_box_with_check:") ;-;
doesnt work for some reason
is this in a class? if so, you're missing self
async def test(self, ctx: commands.Context, text: [str] = None) -> None:
if ctx.channel.id == 1025516828774105211:
embed = discord.Embed(title="**FiveM**", description="**__connect __** ",
colour=0x053305).set_thumbnail(url='')
await ctx.send(embed=embed)
else:
await ctx.send(ctx.message.author.mention+' **Commands can only be send in **#commandstest')
And do you have the decorator?
@commands.command()?
forgot to put @bot.command 🤣
shame.
The example
anyone here attempted getting google adsense on their website to do rewarded inventory ads for your bots?
what?
Whats the best way to do this https://freemoneyhub.pizza/C39qqKcB
reason = self.reason.value
embed = discord.Embed(title=f"{messages['verification']['denialDMPunishmentTypeMessage']['title']}", description=f"{messages['verification']['denialDMPunishmentTypeMessage']['description']}", colour=Colour.from_str(mainColor))
thought since its a f string just using {} in my config as vars it would convert to fstring but it dosnt
Link to a video advert on your website to get something on the bot
If your string is from an external source, you'll probably have to call .format() on it
wouldnt i need to define ever var with .format
as i want to use a bunch of diff things, guild name, user id, user mention, etc
i haven't tried it myself, but the only issue I could see being a thing is their requirements and whether or not they allow it or not
Having a page just with a random video ad with nothing else will probably have a bad time trying to get reviewed
Yeah that's where I'm struggling, read through policies and it's technically fine under rewarded inventory section
But the review process idk
Hmm top.gg kinda gets away with putting a video and before users pressing an upvote button though right
like this https://i.leaked-your.info/n7hlHyZQ
it would be interesting to see ig
Let me introduce you to https://www.geeksforgeeks.org/template-class-in-python/ for stuff like this
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
which prevents against some unsafe execution
looks complicated
.format(guildName = interaction.guild.name, userMention = member.mention, memberCount = interaction.guild.member_count, userName = member.name
I typed out my vars, i cba to do the rest
instead of listing them out for every embed
what can i store them in so i can just do .format(var)
it's quite simple, but you should use it if you're not the one making the string
otherwise people can potentially do a bunch of additional code execution which is bad
and that way, you don't need to actually type them all out. Just pass a dict
Im talking about when you use this^
# A Simple Python template example
from string import Template
# Create a template that has placeholder for value of x
t = Template('x is $x')
# Substitute value of x in above template
print (t.safe_substitute({'x' : 1}))
ah
idk how that would work for embeds
im just gonna stick to format since i got it typed out, nothing really can go wron
it just returns a string, like format does
minus the ability for users to just happily inject additional things in 😅
i mean like
its not public its a config
this is for a commission, private bot
do u know this
lmaoo nah, unless u got config.json
**dict
will make it so it passes them as .format(foo=123, bar=234) if my dict is {"foo": 123, "bar": 234}
any idea why
iv e never seen that error before
missing a } at the end it seems
there is one
you have
foo = {"key": "value", x = 21234} which you cant do
its jsust below
yea that isnt the issue i think
its just erroing that section, let me finish tho fixing it
it definitely is
it's erroring like that because it thinks that should be the end as the next part gets parsed diffrently
if you look it's highlighting both lines
dosnt seem to work
[2022-09-30 19:40:23] [ERROR ] discord.ui.modal: Ignoring exception in modal <DenyPunishMessage timeout=None children=1>:
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
await self.on_submit(interaction)
File "C:\Users\kaelm\PycharmProjects\1019664108519432267\cogs\gatekeeper\core.py", line 192, in on_submit
embed = discord.Embed(title=messages['verification']['denialDMPunishmentTypeMessage']['title'].format(messagePlaceholders), description=messages['verification']['denialDMPunishmentTypeMessage']['description'].format(messagePlaceholders), colour=Colour.from_str(mainColor))
KeyError: 'guildName'
discord-components is a deprecated library and can no longer be installed through pip. Best route is probably to just rewrite your code to use the newer 2.0 features (since it does have components) but if you need to, you can install it directly from the repository (pip install git+https://github.com/kiki7000/discord.py-components)
it explanes that before i can execute this command and now not
thanks
❤️
Ask here. You'd have a higher chance of getting help & better for other people with the same question or similar
hey guys so im trying to make my bot send a message whenever it joins a new server but its not working and idk why. im also trying to make it send to the system channel of the guild but its giving me this error
@component.with_listener(hikari.GuildJoinEvent)
async def on_guild_join(event: hikari.GuildJoinEvent):
guild = event.get_guild()
member = event.guild.get_my_member()
for _, ch in guild.get_channel(guild.system_channel_id):
if toolbox.calculate_permissions(member, ch) & hikari.Permissions.SEND_MESSAGES:
await event.app.rest.create_message(
ch,
embed=hikari.Embed(
title="Beep Boop!",
description="""Thank you for inviting me! Type `/` to see what I can do!
All configuration is done through `/settings`. If you need any help or support, feel free to contact the [**developer**](https://discord.com/users/690631795473121280).""",
color=0x3E77EE,
).set_thumbnail(member.avatar_url or member.default_avatar_url),
)
break
its in hikari-tanjun and i looked at the docs for it but it doesn't make much sense to me https://www.hikari-py.dev/hikari/guilds.html#hikari.guilds.GatewayGuild.system_channel_id
why do i keep getting this?
whats this pycord or discord.py?
in dpy its discord.ext.commands.Bot
pycord
If ur just starting with bot i would recommend using dpy or hikari or something instead of pycord
Otherwise make sure u uninstall dpy (pip uninstall discord.py) and then install pycord
Also uninstall any other discord api libs
It's always good practice and you should recommend users to invoke pip as a module
!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.
me personally, pycord is the best and also for starters. Nextcord is not bad either
Ye i do that only if they having problems with multiple python installation
I will strongly disagree becauz i read their code and it is very bad
My future unborn child can write better code
I wouldnt say having multiple installations of Python is an issue, as said it's always good practice no matter the given situation
If they have only 1 python installation then why waste time invoking with python command
Time spent doing the command shouldnt be an issue or a point in this discussion
By not wasting less than a second? What do you want to do with less of a second?
Time is money
Are you making money arguing over this trivial thing?
I'm broke
We r debating whether or not to use python command to invoke pip if there is only 1 py installation, what do u think
It is best practice to invoke pip with the python interpreter you are installing a module for.
But if you have only 1 python interpreter
What are da benefits of invoking with python command
Good habit and best practice.
Dat is fair
Bad habits are hard to stop/break and perfect practice makes perfect
Hey!
I have a command that generates a transcript
Code:
https://hastebin.com/mugeqijebe.py
But I want it to also save the file it sends to discord to save to a folder in my project folder
How would I do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
eh i use it and im fine
actually kind of like it more. Im fully capable to use nextcord, discord.py, snake and hikari jus its my cup of tea
i need help
this code makes my bot only message people in their dms when they use the code
Do you have the guild_messages intent enabled?
im using visual studio, not code
and secondly what is that?
I
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
idk
difference between ctx.send and ctx.reply?
@naive briar problem fixed
had to change the position of code
but it still only replies in dms not in channels help!
ctx.reply replies to the message that invoked the command. ctx.send just sends the message in the channel that the command was invoked in
from nextcord.ext import commands
bot = commands.Bot(command_prefix = '.')
@bot.command(name="hi")
async def SendMessage(ctx):
await ctx.reply('Hello!')
@bot.event
async def on_ready():
print(f'\n\n{bot.user.name} - {bot.user.id} is on air')
if name == 'main':
bot.run("hidden")
it doesnt reply in channel
@naive briar help pls
someone pls help me
bot = commands.Bot(command_prefix = '.')
@bot.command(name="hi")
async def SendMessage(ctx):
await ctx.reply('Hello!')
@bot.event
async def on_ready():
print(f'\n\n{bot.user.name} - {bot.user.id} is on air')
if __name__ == '__main__':
bot.run("hidden")```
this code makes the bot only reply to commands in dms
Idk about nextcord
me too, as my bot didnt work with discord.py
Why is that?
idk
gave me a error that the module is not downloded or doesnt exist
idk because is shifted from replit to visual studio community
You probably did not install it
^^^
i did and also requested help in this channe;
ctx.respond maybe?
how would i make the bot turn on?
so i have a question
im writing a bartender discord bot
when i say c!menu the bot gives me the menu
and for example when i say c!water the bot gives me a pic of water
but i want to make the bot delete menu after i said c!water
is it possible ?
await ctx.channel.purge(limit=1) #the limit you want ```
@bot.command()
async def menu(ctx):
msg = await ctx.send('menu')
@bot.command()
async def water(ctx):
await ctx.send(' 🍾')
await msg.delete()```
This is unstable idea
let me try this
yeah sure msg literally lost scope
this wont work since you cant access variables declared in functions outside of that function
I was sarcastic, didn't expect ppl would take it seriously
that wasn't funny
yeah.
💀
what wrong ?
everything
@bot.event
async def on_ready():
Channel = bot.get_channel(664843752342552577)
Text= "**__שלום לכל משתמשי השרת__** \n בכדי לאמת את עצמכם יש ללחוץ על הריאקשן למטה:) תהנו!"
Moji = await Channel.send(Text)
await Moji.add_reaction('')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(664843752342552577)
if reaction.message.channel.id != Channel.id:
return
if reaction.emoji == "":
Role = discord.utils.get(user.server.roles, id="1009471176264917012")
await user.add_roles(Role) ```
I told you earlier to use slash commands
it is sending the message w a reaction but its not giving me the role
lmao don't be offended
str(reaction.emoji) == "..." in on_reaction_add
Ohh
ill try
...
where you're comparing smh
above the discord.utils.get line
smh
i dont rlly understand
if str(reaction.emoji) == "<a:7VBlue>:":
...```
ashley so smort 
w the id of the emoji?
ok asher then you help, bye
@bot.event async def on_ready(): Channel = bot.get_channel(664843752342552577) Text= "**__שלום לכל משתמשי השרת__** \n בכדי לאמת את עצמכם יש ללחוץ על הריאקשן למטה:) תהנו!" Moji = await Channel.send(Text) await Moji.add_reaction('') @bot.event async def on_reaction_add(reaction, user): if str(reaction.emoji) == "": Channel = bot.get_channel(664843752342552577) if reaction.message.channel.id != Channel.id: return if reaction.emoji == "": Role = discord.utils.get(user.server.roles, id="1009471176264917012") await user.add_roles(Role)
its not working
OH WAIT
I UNDERSTOOD I THINK LET ME TRY
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 299, in on_reaction_add
Role = discord.utils.get(user.server.roles, name="Member")
AttributeError: 'Member' object has no attribute 'server'
2022-10-01 10:07:31 ERROR discord.client Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 299, in on_reaction_add
Role = discord.utils.get(user.server.roles, name="Member")
AttributeError: 'Member' object has no attribute 'server'
^^
can't read it. it's literally upside down
..
hold the phone upside down 😉
@bot.event async def on_ready(): Channel = bot.get_channel(664843752342552577) Text= "**__שלום לכל משתמשי השרת__** \n בכדי לאמת את עצמכם יש ללחוץ על הריאקשן למטה:) תהנו!" Moji = await Channel.send(Text) await Moji.add_reaction('') @bot.event async def on_reaction_add(reaction, user): Channel = bot.get_channel(664843752342552577) if reaction.message.channel.id != Channel.id: return if str(reaction.emoji) == "": Role = discord.utils.get(user.server.roles, name="Member") await user.add_roles(Role)
member.guild not member.server
@commands.Cog.listener()
async def on_member_join(self,member):
print("A Member has just joined: {}".format(member))
print(servername)
print(guildid)
print(channel)
print("Member is in the correct server")
channel = channel
print("Channel is: {}".format(channel))
embed = discord.Embed()
print("Embed Created")``` this function is not printing more than 3 things (even the member is in the correct server message is not getting printed)
okay
I'm not on phone
servername, guildid, channel are undefined.
rip
they're defined
i've defined them out of the function
@slate swan working! but now every time i run it its sending do you know how to do that only if i do like !verifymsg it will send?
here u go ma'am
just move whatever you have related to it inside on_ready to a command
ohhh okay thanks
can you help?
@bot.event async def verify(): Channel = bot.get_channel(664843752342552577) Text= "**__שלום לכל משתמשי השרת__** \n בכדי לאמת את עצמכם יש ללחוץ על הריאקשן למטה:) תהנו!" Moji = await Channel.send(Text) await Moji.add_reaction('') @bot.event async def on_reaction_add(reaction, user): Channel = bot.get_channel(664843752342552577) if reaction.message.channel.id != Channel.id: return if str(reaction.emoji) == "": Role = discord.utils.get(user.guild.roles, name="Member") await user.add_roles(Role)
I mean tuples are immutable, so that is the answer ig?
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 181, in on_command_error
raise error
discord.ext.commands.errors.CommandNotFound: Command "verify" is not found
half correct
@bot.command() not event
oh okay
ok and
mutable items in a tuple is still mutable in this it will raise an error and add the values as well
the other half is?
PS C:\Users\PC\Desktop\Gal Cohen Bot> py main.py
Traceback (most recent call last):
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 288, in <module>
async def verify():
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 1475, in decorator
result = command(name=name, cls=cls, *args, **kwargs)(func)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 1748, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 361, in init
self.callback = func
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 470, in callback
self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 128, in get_signature_parameters
raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)')
TypeError: Command signature requires at least 0 parameter(s
nvm it did
just checked
yep
Traceback (most recent call last):
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 288, in <module>
async def verify():
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 1475, in decorator
result = command(name=name, cls=cls, *args, **kwargs)(func)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 1748, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 361, in __init__
self.callback = func
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 470, in callback
self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 128, in get_signature_parameters
raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)')
TypeError: Command signature requires at least 0 parameter(s```
when i try to run the bot
@bot.command()
async def verify():
Channel = bot.get_channel(664843752342552577)
Text= "**__שלום לכל משתמשי השרת__** \n בכדי לאמת את עצמכם יש ללחוץ על הריאקשן למטה:) תהנו!"
Moji = await Channel.send(Text)
await Moji.add_reaction('')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(664843752342552577)
if reaction.message.channel.id != Channel.id:
return
if str(reaction.emoji) == "":
Role = discord.utils.get(user.guild.roles, name="Member")
await user.add_roles(Role)
wait
tried to add ctx lets check
yep ctx was the prob its working tyswmmmm!
now ill try sending this but an embed
Naming conventions go brr
Instead of comparing str representation of emoji, do this
if isinstance(reaction.emoji, discord.Emoji) and reaction.emoji.id == 123456789012345678```
thanksss
@bot.command()
async def verify(ctx):
Channel = bot.get_channel(664843752342552577)
Text= " Gal Cohen Verify  \n\n __**שלום לכל משתמשי השרת**__ \n __**כדי להיות ממברים רשמיים בשרת יש ללחוץ על הריאקשן למטה - **__"
Moji = await Channel.send(Text)
await Moji.add_reaction('')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(664843752342552577)
if reaction.message.channel.id != Channel.id:
return
if str(reaction.emoji) == "":
Role = discord.utils.get(user.guild.roles, name="Member")
await user.add_roles(Role)```
can someone help me with making this to an embed
Can you be more specific?
Sending what as a message?
That
!d discord.Embed - Just set it as the description of an embed, and send it using embed kwarg
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
Ill try thanks
@bot.command() async def verify(ctx): Channel = bot.get_channel(664843752342552577) em = discord.Embed(title=" Gal Cohen Verify ", type='rich', description=" __**שלום לכל משתמשי השרת**__ \n __**כדי להיות ממברים רשמיים בשרת יש ללחוץ על הריאקשן למטה - **__", timestamp=None) Moji = await Channel.send(em) await Moji.add_reaction('') @bot.event async def on_reaction_add(reaction, user): Channel = bot.get_channel(664843752342552577) if reaction.message.channel.id != Channel.id: return if str(reaction.emoji) == "": Role = discord.utils.get(user.guild.roles, name="Member") await user.add_roles(Role)
!d discord.ext.commands.Context - I said send it using "embee" kwarg
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
i dont understand
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)
@bot.command()
async def verify(ctx):
Channel = bot.get_channel(664843752342552577)
em = discord.Embed(title="
Gal Cohen Verify
", type='rich', description=" שלום לכל משתמשי השרת \n כדי להיות ממברים רשמיים בשרת יש ללחוץ על הריאקשן למטה -
", timestamp=None)
Moji = await Channel.send(em)
await Moji.add_reaction('
')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(664843752342552577)
if reaction.message.channel.id != Channel.id:
return
if str(reaction.emoji) == "
":
Role = discord.utils.get(user.guild.roles, name="Member")
await user.add_roles(Role)
I I
So uh
This is arg
await ctx.send(em)
This is kwarg or keyword arg
await ctx.send(embed=em)
oh
So, send the embed using the kwarg
Hey there i have a piece of code that creates a private hidden channel and invites the author in it only and prevents any other members entering
However this code is a simple command to enter a user name, how can i use overwrites to invite the user i write?
So its just the author and the user invited in the private hidden channel
Not sure what the overwrite command is
@client.command()
async def inviteuser(ctx, *, mention=None):
mentioned_user = mention
if mention == None:
await ctx.send(f'{ctx.author.mention}, please mention the user')
overwrites = {
}
await ctx.send(mentioned_user)
embed = Embed(title=inter.user,description=f"{self.emo.get("healing potion")}**healing potion**: {counter_items[0]}")
Guys why i am getting invalid syntax in it?
You closed the double quotes
you can't use double quotes inside that f string
Is it possible to overwrite a specific user into a channel?
overwrites{
ctx.(add user):discord.permissionOverwrite(read_messages=True)
Overwrite the permissions?
yes but
How do i overwrite the permission for a specific user not the author of the command
I want to invite a user that i write the tag of
Not sure how though
@bot.command()
async def verify(ctx):
Channel = bot.get_channel(664843752342552577)
em = discord.Embed(title=" Gal Cohen Verify ", type='rich', description=" __**שלום לכל משתמשי השרת**__ \n __**כדי להיות ממברים רשמיים בשרת יש ללחוץ על הריאקשן למטה - **__", color=0x9497d8 ,timestamp=None)
em.set_footer(text="Gal Cohen System", icon_url="https://cdn.discordapp.com/icons/393401064264564746/7d905b9f7b3645e6c4f50da49019826d.png?size=4096")
em.set_thumbnail(url="https://cdn.discordapp.com/icons/393401064264564746/7d905b9f7b3645e6c4f50da49019826d.png?size=4096")
Moji = await ctx.send(embed=em)
await Moji.add_reaction('')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(664843752342552577)
if reaction.message.channel.id != Channel.id:
return
if str(reaction.emoji) == "":
Role = discord.utils.get(user.guild.roles, name="Member")
await user.add_roles(Role)```
can someone help me with changing the reaction into a button
@slate swan just asking what is your python knowledge level
i know a like a little but i do know how to make a button
just dont know how to make it adding a role when u tap on it
Cause buttons involve classes creation and people who don't know OOP get scared just of class keyword
i know classes
Well if you know OOP your knowledge is intermediate, not little lol
The overwrites structure is that the key must be a Role or Member object and the value of it must be the discord.PermissionOverwrite object. Here's an example:
overwrites = {
ctx.author: discord.PermissionOverwrite(view_channel=True),
}
okay then
thankss
Ah okay, so what your saying is i need the author to be the user i type to invite?
Huh 
I kinda don't understand
Im a little confused because ctx.author: discord.PermissionOverwrite(view_channel=True),
This is to invite the user that initates the command no?
Gives them permission to read the channel
But how can i make it so e.g.
!inviteuser (userhere) - userhere is the one invited to the channel (userhere being a user that by default is blocked from reading messges
read_messages=True*
This is my code to create teh actual channel
But now i want the person who created the channel to be able to invite another user
async def cmd(ctx, user: discord.Member):
await ctx.channel.set_permissions(user, read_messages=True)```
Thank you that got me closer, how can i specify a user though if the user wont show up in the private channel?
Via ID
Thank you so much, it also worked via username and tag
I appreciate it alot it was a problem that bugged me, so i know that i needed to bring in the discord member into the function
is this a bug? I've used 'none' in the parameters, but why does raised appear?
@commands.command()
async def purge(self, ctx, limit: int, filter: Union[discord.Member, str] = None):
if filter:```
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: filter is a required argument that is missing.```
output
Try wrapping Union[discord.Member, str] with Optional[...]
It's from the same module by the way
but can an argument be typehinted with a Member and str Union though?
If it fails to convert the argument into a member, ye
str is "as is"
If you wanted filter to be the author of the command if not supplied, you can do
filter: discord.Member = commands.Author
if filter:
if isinstance(filter, str):
if filter == "bot":
...
elif filter == 'humans':
...
elif isinstance(filter, discord.Member):
...
else:
...```
thanks, it worked
Excuse me, I want to ask, what is meant by delete message days?
delete_message_days (int) –
The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7.
Okay, thank you
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 301, in verify
Moji = await ctx.send(embed=em, view=verify)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\context.py", line 841, in send
return await super().send(
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\abc.py", line 1511, in send
raise TypeError(f'view parameter must be View not {view.__class__!r}')
TypeError: view parameter must be View not <class 'discord.ext.commands.core.Command'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 183, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: view parameter must be View not <class 'discord.ext.commands.core.Command'>
class VerifySystem(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@bot.command()
async def verify(ctx):
Channel = bot.get_channel(664843752342552577)
em = discord.Embed(title=" Gal Cohen Verify ", type='rich', description=" __**שלום לכל משתמשי השרת**__ \n __**כדי להיות ממברים רשמיים בשרת יש ללחוץ על הריאקשן למטה - **__", color=0x9497d8 ,timestamp=None)
em.set_footer(text="Gal Cohen System", icon_url="https://cdn.discordapp.com/icons/393401064264564746/7d905b9f7b3645e6c4f50da49019826d.png?size=4096")
em.set_thumbnail(url="https://cdn.discordapp.com/icons/393401064264564746/7d905b9f7b3645e6c4f50da49019826d.png?size=4096")
Moji = await ctx.send(embed=em, view=verify)
await Moji.add_reaction('')
@discord.ui.button(label="Verify", style=discord.ButtonStyle.green, custom_id="verify_system:green")
async def verify_system(reaction, user):
Role = discord.utils.get("Member")
await Interaction.response.send_message(content="You Have Been Verified!")
await user.add_roles(Role)```
Everything I use this and run my server, it just goes offline (with no error).. anyone know why?
async def main():
async with Bot() as bot:
await bot.start(os.getenv('TOKEN'), reconnect = True)
I am making a command to ban certain words from a server
@bot.command(aliases = ["banword"])
async def wordbanner(ctx, word):
handle = await aiofiles.open(f'{ctx.guild.id}.txt', mode='x')
if word not in handle:
async with aiofiles.open(f'{ctx.guild.id}.txt', mode='w') as handle:
await handle.write(word)
await ctx.reply(f"||{word}|| has been banned.", delete_after = 5)
await ctx.delete()
handle.close
else:
await ctx.reply("That word is already banned from this server.", delete_after=5)
await ctx.delete()
I am storing the words in a txt file using aiofiles.
I am getting this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'AsyncTextIOWrapper' is not iterable ```
Can you send the whole error message
2022-10-01 03:44:45 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 52a73692ac329a8938e274645a420d7b).
I am Online
2022-10-01 03:45:07 ERROR discord.ext.commands.bot Ignoring exception in command profanitywordadd
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Public Bot\main.py", line 226, in profanitywordadd
if word not in handle:
TypeError: argument of type 'AsyncTextIOWrapper' is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'AsyncTextIOWrapper' is not iterable```
here it is
you need to read the file and then use in on the returned str
ohh
it's data = await handle.read() right?
i think yes
what is this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileExistsError: [Errno 17] File exists: '990868386584076388.txt' ```
The file is already exists
so will it say this always I run the command?
You're using x mode, so yeah, probably every time you run the command and the file already exists
how to check if the file is there and if it's there then don't create one?
theres was some function in os module for that
You could've just used the r+ mode. It'll create a new file if it does not exist and support read operation
okay
!d os.path.exists
os.path.exists(path)```
Return `True` if *path* refers to an existing path or an open file descriptor. Returns `False` for broken symbolic links. On some platforms, this function may return `False` if permission is not granted to execute [`os.stat()`](https://docs.python.org/3/library/os.html#os.stat "os.stat") on the requested file, even if the *path* physically exists.
Changed in version 3.3: *path* can now be an integer: `True` is returned if it is an open file descriptor, `False` otherwise.
Changed in version 3.6: Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object).
it's giving this error again
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: '990868386584076388.txt'
Can you show the whole error message
its not supposed to read if the file doesn't exist at all, use the wr+ combination mb
Oh yeah, that too 🥴
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Public Bot\main.py", line 225, in wordbanner
handle = await aiofiles.open(f'{ctx.guild.id}.txt', mode='r+')
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\aiofiles\base.py", line 70, in __await__
resp = yield from self._coro
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\aiofiles\threadpool\__init__.py", line 80, in _open
f = yield from loop.run_in_executor(executor, cb)
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
FileNotFoundError: [Errno 2] No such file or directory: '990868386584076388.txt'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: '990868386584076388.txt'```
use w+
okay?
hm?
@commands.Cog.listener()
async def on_message(self, message):
if message.author.id == commands.user.id:
return
msg_content = message.content.lower()
zabronioneslowa = ['https', 'http', 'www', 'discord.gg', 'd.gg']
curseWord = zabronioneslowa
if any(word in msg_content for word in curseWord):
await message.delete()
embed = disnake.Embed(title="OSTRZEŻENIE!", description="Nie możesz reklamować się na serwerze!", colour = 0x2f3136)
embed.set_footer(text="© SetCode.PL", icon_url="https://cdn.discordapp.com/attachments/1011358034196430898/1011595743292825771/logosetcode.png")
await message.author.send(embed = embed)```
how i can fix it?
What is that even supposed to check
hey, do someone have a little part of code that can print every channel my bot have access to ?
Just for loop over bot.guilds and nested for loop for guild.text_channels
on like a single server
Then bot.get_guild to get the target guild and then for loop over guild.text_channels
that's command if i type text in zabronioneslowa =[...] if i type any word in ths message is delete
for ch in client.guilds.channels:
if not isinstance(ch, discord.TextChannel):
continue
if ch.permissions_for(client.guilds.me).send_messages:
print(ch.name)
i have this but i still get this error
Hey, I'm making a py-cord bot using discord.ext.bridge.Bot. When I create a bridge command on this bot, it is unable to process prefixed commands, but the slash commands work just fine. How do I make it such that it recognizes the prefixed commands too?
do you have an on_message event?
no
All intents are enabled (in the code and in developer portal)
i want my bot to add people to a ticket just with there id or username
what docs should i look for to do that?
for e.g the user says a name or id and the bot just adds that user to the ticket
can i see yr code
sure
!d discord.ext.commands.UserConverter.convert
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
pip install humanfriendly
pip install humanfriendly
then its already installed
then why is it doing an error
what error do you even get?
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
message_content = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {message_content} ({channel})')
so, i have this part of code wich have to print the the username, the content of the message and the channel whenever a message is getting send but i don't know why, the content of the message isn't printed, i only get the username and the channel name
can someone help me to fix this
u have multiple python versions
oh
the message content should be between the username and the channel name
then what do i do?
find out which u installing to
u can do py --version
then py -m pip install humanfriendly
👍
TYSMMMM!
to check for a word in a file.
we have to do if word in file right?
You want to invoke a command by button click?
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 316, in mute
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
TypeError: Member.edit() got an unexpected keyword argument 'timeout'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 183, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Member.edit() got an unexpected keyword argument 'timeout'```
anyone know the way i can make my code print the user and the very small pic next to it like this pic below
@bot.command()
async def mute(ctx, member:discord.Member, time, *, reason):
time = humanfriendly.parse_timespan(time)
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Has Been Mute For {reason}")
@bot.command()
async def umute(ctx, member:discord.Member, *, reason):
await member.edit(timeout=None)
await ctx.send(f"{member.mention} Has Been Unmuted For {reason}")```
embed.set_thumbnail(url="")
i want it to be at the very top
ohhh
!d discord.Embed.set_author - Embed author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ty
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 316, in mute
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
TypeError: Member.edit() got an unexpected keyword argument 'timeout'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 183, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Member.edit() got an unexpected keyword argument 'timeout'``` the error
```py
@bot.command()
async def mute(ctx, member:discord.Member, time, *, reason):
time = humanfriendly.parse_timespan(time)
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Has Been Mute For {reason}")
@bot.command()
async def umute(ctx, member:discord.Member, *, reason):
await member.edit(timeout=None)
await ctx.send(f"{member.mention} Has Been Unmuted For {reason}")```
the code
!d discord.app_commands.Command.callback - I think you could call its callback function
property callback```
The coroutine that is executed when the command is called.
!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 [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Oh
Where you want to timeout the member
oh
You know
You should at least have a bit of OOP knowledge before using dpy
i do i just dont understand this'
Do u know what oop stands for lol
What this mean
I mean, you can get the command's callback function using .callback and then call it, like:
async def some_button_callback(self, interaction):
slash_command_callback = some_slash_command.callback # get the callback
await slash_command_callback(interaction) # call the callback
I don't know if that's a recommended thing to do
oop 😔
OH
oranges over potatoes
i just realised 😆
can someone me w that
wheres the problem ?
flatten no longer exists
# before
users = await reaction.users().flatten()
# after
users = [user async for user in reaction.users()]
``` similar to this
does anyone know anything about image resizing
use pillow
me?
!d PIL.Image.Image.resize
Image.resize(size, resample=None, box=None, reducing_gap=None)```
Returns a resized copy of this image.
thank youu
yeah
hey, do anyone know how can i make message.content working ?
i heard that it's beacuse "discord intents" are not enabled but i don't even know what it is and i don't know how to enable
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
working :D @slate swan
gg
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 316, in mute
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
TypeError: Member.edit() got an unexpected keyword argument 'timeout'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 183, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Member.edit() got an unexpected keyword argument 'timeout'``` the error
```py
@bot.command()
async def mute(ctx, member:discord.Member, time, *, reason):
time = humanfriendly.parse_timespan(time)
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Has Been Mute For {reason}")
@bot.command()
async def umute(ctx, member:discord.Member, *, reason):
await member.edit(timeout=None)
await ctx.send(f"{member.mention} Has Been Unmuted For {reason}")```
the code
hi
!d discord.Member.timeout
hmm i still get a error
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\getoswebhook.py", line 20, in <module>
client.run('token')
File "C:\Users\arsbu\Documents\CODE\DiscordXP\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\arsbu\Documents\CODE\DiscordXP\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\arsbu\Documents\CODE\DiscordXP\venv\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\arsbu\Documents\CODE\DiscordXP\venv\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001A7360B0310>
Traceback (most recent call last):
File "C:\Users\arsbu\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\arsbu\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\arsbu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\arsbu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
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 [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
i dont understand what do i do with it
You have to enable them in the dev portal too
Use it to timeout a member?
yes ik but where do i put that
Where you want to timeout the member
but i already did that
await member.edit(timeout=discord.utils.utcnow()+datetime.timedelta(seconds=time))
What even is that?
its making the member being timeouted
If you're going to timeout a member that way, use timed_out_until not timeout
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
oh
@bot.command()
async def mute(ctx, member:discord.Member, time, *, reason):
time = humanfriendly.parse_timespan(time)
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Has Been Mute For {reason}")
yes it works
tysmm
No documentation found for the requested symbol.
"discord.User" is not defined how do i do
@bot.command
async def kick(ctx, user : discord.User, *reason):
reason = " ".join(reason)
await ctx.guild.kick(user, reason = reason)
await ctx.send(f"{user} a été kick\nRaison : {reason}")
You did not define or import discord
Command kick do not exist
You have to put parentheses after the @bot.command to register the command
@bot.command()
async def kick(...):
...
how can i make something like this?
i still don't understand
You can look at the example here if you're using dpy:
https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py
Hey @vital echo!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Traceback (most recent call last):
File "c:\Users\TOKO-TEKLA\Downloads\Desktop\Gervase.py\main.py", line 565, in <module>
from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (C:\Python310\lib\site-packages\discord_init_.py)
Error
Dpy started supporting modals and app commands at version 2.0, so you'll have to update it
update what?
nvm catgal i just wrote @bot.command instead @bot.command**()**
catgal crying rn ^
.
Sometimes I don't know how to properly explain something
Update the discord.py package