#discord-bots
1 messages Β· Page 938 of 1
just edit the message with a new embed?
async def giveaway(self, ctx, time, *, prize):
giveawayembed = nextcord.Embed(
title="π New Giveaway! π",
color=0xfd9fa1
)
time=humanfriendly.parse_timespan(time)
giveawayembed.add_field(name="Prize", value="{}".format(prize), inline=False)
giveawayembed.add_field(name="Hosted by", value=f"{ctx.author.mention}", inline=False)
giveawayembed.add_field(name="Ends in", value="{}".format(time))
msg = await ctx.send(embed=giveawayembed)
giveawayembed = nextcord.Embed(
title="π New Giveaway! π",
color=0xfd9fa1
)
time=humanfriendly.parse_timespan(time)
giveawayembed.add_field(name="Prize", value="{}".format(prize), inline=False)
giveawayembed.add_field(name="Hosted by", value=f"{ctx.author.mention}", inline=False)
giveawayembed.add_field(name="Changed", value="{}".format(time))
await msg.edit(embed=giveawayembed)
!d discord.Message.edit | in the embed kwarg set a duplicate embed with the new content in it
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
uhh when i tried this code, the bot sent this
Command raised an exception: TypeError: expected string or bytes-like object
....?
I copied your code and added the same onto it with a string changed

bots have nitro
yeah i replaced my code with that and it threw me errors when i tried to make a giveaway
Okey can i solve this problem this way: despite sending button i will ask people to send any message to a channel. This way everything will work?
Using bot.wait_formessage
uh yeah if your bot takes its time between muting and unmuting people
button should work the same
bots already have that ability similiar to nitro users.
if I click on every emoji in my reaction roles, my reactions are gonna lag even tho the problem's on the bot side
or is it just discord
:(
shouldnt use reactions tbh. ratelimits are high on reactions compared to buttons and overall buttons are better

Yes i had this trouble using reactions, and i started using buttons
But now when 200 people in one moment press these buttons
Everything crashes
better than your bot waiting for 200 on reaction gateway events
i mean you can just use a event but in your case youre using wait for
but events are the same so it wouldnt matter
so all this conversation was pointless
async def startGame(ctx, gameID: int = 2):
is always making gameID == 2 even if i say /start_game 1
how would i fix this?
Why doesn't the "mongo" database add more than 4 members to the database list?
im catching up on alex's problem, they're using wait_for to listen for buttons?
It shouldn't be like that.
Try re-running your code.
This isn't related to Discord bots
yeah no shit, but it is
Try asking in #databases
Can you show more code?
I make an economic bot
Your question isn't relevant to this channel's topic.
not really sure myself i just know he was using wait for, well he told me he was using reactions as buttons but hes probably using an event so nvm everything i said
ok, sorry
well it could be, if the problem happened to be related to dpy functionality
The question was too vague, it's hard to make that argument.
And they mentioned the database instead of anything related to dpy breaking
as such, @swift imp you need to share your code and a bit more explanation on what exactly you did for us to figure out if its something wrong with your discord implementation
hey 1 thing
if i wanna make a public bot and learn python how can i learn where should i start from ? >> and when i make a public bot i need a DB ? so how do i make one and use it ty for any help
It's not necessary that if you make a public bot you'll need a database, depends on the functionality of the bot
- learn basic python
- learn intermediate python
- learn oop
- learn async programming
that was mostly my process
yes u say learn it but where do i learn it from
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
okay, 1 second
the most powerful weapon available
Weapon?
for oop you can search up Corey Schafer async programming probably docs @tacit moss
Sure.
hey guys is there something like on_raw_reaction_add but for adding roles and removing roles?
wish i could link tutorials but im on mobile
Why do you need a raw event for that?
cluster = MongoClient("my link for db")
db = cluster["bdcluster"]
collection = db["bdcollecltion"]
@bot.event
async def on_ready():
print('Bot ready')
for guild in bot.guilds:
for member in guild.members:
post = {
"_id": member.id,
"money": 0,
}
if collection.count_documents({"_id": member.id}) == 0:
collection.insert_one(post)```
adding/removing from members? on_member_update is good enough
thanks
To trigger a piece of code, each time a user adds roles to some1
is there a raw event for it?
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
β’ nickname
β’ roles
β’ pending...
You don't need a raw event, that's pointless.
Oh okay, then thanks!!
Raw events exist for message events and such because it's not guaranteed that dpy will have the message object cached
And Discord only sends partial data for such events
ah yea ive noticed that
this is what i mean tho lets say i have 2 servers and the bot is in both >> 1 server the prefix is ! >> and the other server prefix is + do u need a data base for that ?
what intents did you pass to your bot? and how many guilds is your bot in
discord.Intents.all(), 3
Most databases are for storing data long term. You can start by caching the prefixes and then experimenting with databases.
can you show the line where you construct your bot just to double check
thats the problem i dont understand that stuff yet i dont know how that works but i want 2 learn
intents = discord.Intents.all()
bot = commands.Bot(command_prefix ='h!', help_command=None, intents=intents)
are there more than 4 unique members/bots across your guilds? looking at your find_one call you dont include the guild id as a key, so each document would (or should) be globally unique
oh wait a minute
@swift imp
btw you should use an async lib for handling a mongo database like motor, otherwise every call to your database would slow down your bot
@slate swan so what should i 1st do on a bot
all guilds have approximately 600 members
okay
maybe not a good idea to attempt inserting 600 posts every time you restart your bot
yeah
only add a document when they do something like sending a message/using a command that requires checking their money
that way you dont burden your startup with lots of requests
load_extension you should probably do outside of on_ready
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str) -> None:
msg = await ctx.send(echo)
await msg.add_reaction("β
")
await msg.add_reaction("β")
await ctx.message.delete()
channel = ctx.channel
def check(reaction, user, ):
return user == ctx.author and str(reaction.emoji) in {'β
', 'β'}
try:
reaction, user = await bot.wait_for('reaction_add', check=check)
except asyncio.TimeoutError:
await channel.send('you timed out...')
return
if str(reaction.emoji) == 'β
':
await channel.send('Gotcha! order confirmed')
channel2 = discord.utils.get(ctx.guild.channels,name = f"private-channel{ctx.author}")
channel3 = ctx.guild.get_channel(channel2.id)
await channel3.send(f"<@{user_id}> \n {echo} ")
await msg.add_reaction("β
")
await msg.add_reaction("β")
channel =ctx.channel
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in {'β
', 'β'}
try:
reaction, user = await bot.wait_for('reaction_add', check=check)
except asyncio.TimeoutError:
await channel.send('you timed out...')
return
if str(reaction.emoji) == 'β
':
return
else:
return
else:
await channel.send('Understood! cancelling order!')
AttributeError: 'NoneType' object has no attribute 'id' for line channel3 = ctx.guild.get_channel(channel2.id)
@craggy cloak for example: ```py
bot = commands.Bot(...)
async def main():
await bot.load_extension('folder.filename')
async with bot:
await bot.start(TOKEN)
asyncio.run(main())```
That can't be client?
the variable name? sure it can
but if you're using commands.Bot then its kind of weird to name it based on another class
any help would be much apricated
how can i make a bot respond so when i say a number it adds 1 to it?
example
human: 234
bot: 235
int(message) + 1
How change background in ConEmu?
Who is not difficult to explain, I already searched all the settings and didnβt find
What's ConEmu
It's a cmd
How is this relevant to this channel?
I don't know
most discord data you're going to store is well suited for relational databases (per-guild prefixes and settings or per-member currency)
any help?
not here π€·ββοΈ
not in all server or only this channel ?
in this server
No
is there a list of all the events a bot can wait for?
any help is apricated
{ctx.author} gets formatted like name#discriminator, and channel names definitely cant have # in them
I'm looking under the docs for discord.py but I can't find anything
I'm checking under events, wait_for, etc
okay, thanks
@supple crescent also if a valid name was provided then discord.utils.get() would return a channel object for you, so no need to get it again for channel3
so just remove that line altogether?
yeah
lets try it
you're going to need a more robust way of storing the private channel that corresponds to the author
fuck ok im jut gonna restart this part
writing their user id in the channel name could work, although it wont look that good
code -
class Select(Select):
def __init__(self):
options=[
discord.SelectOption(label="Option 1",emoji="π",description="This is option 1!"),
discord.SelectOption(label="Option 2",emoji="β¨",description="This is option 2!"),
discord.SelectOption(label="Option 3",emoji="π",description="This is option 3!")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
@client.command()
async def menu(ctx):
await ctx.send("Menus!",view=Select()
)
error - ```py
Traceback (most recent call last):
File "main.py", line 42, in <module>
class Select(Select):
NameError: name 'Select' is not defined
ξΊ§
nah im just gonna use a workaround @hushed galleon
i tried 20 differ things
thanks tho
did you mean to subclass discord.ui.Select?
Traceback (most recent call last):
File "main.py", line 42, in <module>
class Select(discord.ui.Select):
AttributeError: module 'discord' has no attribute 'ui'
then you need to upgrade to dpy 2.0 / master
i am?
are you sure
basically I'm wondering if theres a wait_for(event="attachment") or something
did you name one of your scripts discord.py?
if you have the right version installed yes
can u send the one
like the install link?
yes
pip install git+https://github.com/Rapptz/discord.py, although on repl.it i believe you should edit poetry.lock rather than run pip in the shell directly
i shold edi it?
[tool.poetry]
name = ""
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "^3.8"
psutil = "^5.9.0"
requests = "^2.27.1"
discord = "^1.7.3"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
yeah replit didnt even install the correct package, they used the mirror package
replace the discord line with "discord.py" = {git = "https://github.com/Rapptz/discord.py"}
ur the best
in the repo there's examples of how to use views with buttons/selects
[tool.poetry]
name = "python-template"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "3.9"
numpy = "^1.22.2"
"discord.py" = {git = "https://github.com/Rapptz/discord.py"}
bs4 = "^0.0.1"
requests = "^2.27.1"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
@hushed galleon sorry to bother, how would i get the echo
if str(reaction.emoji) == 'β
':
await channel.send('Gotcha! order confirmed')
channel2 = discord.utils.get(ctx.guild.channels,name = f"private-channel{ctx.author}")
await channel2.send(f"<@{user_id}> \n {echo} ")
await msg.add_reaction("β
")
await msg.add_reaction("β")
to work without getting the nonetype error?
wait do i add
discord = that or
nah the entire line should be replaced
oki
you can check if its none before sending a success message
check if what is none?
the... channel you tried getting
ah
hey
is this right ```py
[tool.poetry]
name = "python-template"
version = "0.1.0"
description = ""
authors = ["Your Name you@example.com"]
[tool.poetry.dependencies]
python = "3.9"
numpy = "^1.22.2"
"discord.py" = {git = "https://github.com/Rapptz/discord.py"}
bs4 = "^0.0.1"
requests = "^2.27.1"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
yeah
Traceback (most recent call last):
File "main.py", line 42, in <module>
class Select(discord.ui.Select):
AttributeError: module 'discord' has no attribute 'ui'
still this error?
no
can you check the pyproject.toml file again
ok im here
i just tested it and replit incorrectly added the discord package
yeah they try to analyse your imports and install packages for you
how would i do thart
clearly doesnt seem to work well
as in how would you turn off package autoinstall? i dont know
no, because the real package isnt named discord
its supposed to be discord.py
replit writes discord because what they're actually installing is the mirror package named discord which is just a copy of discord.py 1.7.3
ask your question and someone will respond
wait so if i did discord 2.0.0
2.0 isnt actually on pypi
right now its just another name for the master branch on the discord.py repository
hey @hushed galleon i made it work , but how do i make a reply for EACH embed?
option*
in your callback you can tell which option was selected from the self.values list
its shown in one of their examples on github https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py#L11-L31
whats confusing about the example on the repo
it shows you how to get the option that the user selected
you can figure out how to make different embeds based on the value
can u show
seriously its as simple as a few if-statements
and does this if i were to print it
yeah a string surrounded by two underscores gets underlined
is there anyway to fix that
!d discord.utils.escape_markdown
discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)```
A helper function that escapes Discordβs markdown.
ok thanks
heyy = discord.Embed(title=discord.utils.escape_markdown(unbury))```i did this but it still makes a line
class ColourView(discord.ui.View):
options = [
discord.SelectOption(label='Red is fire!', value='red'),
discord.SelectOption(label='Blue is cooler!', value='blue')
]
@discord.ui.select(options=options)
async def on_select_colour(self, interaction, select):
choice = select.values[0]
if choice == 'red':
await interaction.response.send_message('good choice')
else:
await interaction.response.send_message("you're wrong")```
bro omg tysm
line 25, in profile
userfail = discord.Embed(title=f"{user.name} is not found.")
UnboundLocalError: local variable 'user' referenced before assignment```
```py
async def profile(self, ctx, username):
try:
user = await roblox.get_user_by_username(username)
embed = discord.Embed(
except UserNotFound:
userfail = discord.Embed(title=f"{user.name} is not found.")
await ctx.send(embed = userfail)```
if it raises UserNotFound as it tries calling get_user_by_username(username), then user wont be defined
you probably meant to just display username
hm you're right, i think it still collapses the characters despite being escaped
NameError: name 'select' is not defined
oh so userfail = discord.Embed(title=f"{username} is not found.")
i could use dashes but thats just ugly
wait nevermind i tested with the wrong variable, works fine for me
i want it to not make a line
oh as in separate with spaces?
yeah
@hushed galleon i see your helping alot of people, if you can help you when u got time its hust that error i sent
NameError: name 'select' is not defined
the example i sent used the decorator form which passes the Select object as a parameter, earlier you were using a class for the Select itself so you'd write self.values instead
well you have the join already, make it join with spaces instead of nothing
yup got it thanks
fixxed but new error againn TypeError: 'property' object is not subscriptable
i think i fixxed
you didnt write Select.values[0] did you
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji=':red_square:'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji=':green_square:'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji=':blue_square:'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
choice = Dropdown.values[0]
if choice == 'Red':
await interaction.response.send_message('good choice')
else:
await interaction.response.send_message("you're wrong")
no, Dropdown is just a generic class, it doesnt contain the actual data that discord provided
I cant find anything very useful in the documentation or online about this specific topic...
How would I go about changing a role or multiple roles permissions on a single channel?
you would edit the permission overwrites of the channel
!d discord.abc.GuildChannel.overwrites
property overwrites```
Returns all of the channelβs overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
e.g. ```py
overwrites = channel.overwrites
deny send perms for @everyone and @thegamecracks
overwrites[guild.default_role].send_messages = False
overwrites[member].send_messages = False
await channel.edit(overwrites=overwrites)```
Oh cool, thank you very much
class select(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='π₯'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='π©'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='π¦'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if select.values[0] == 'Red':
await interaction.response.send_message('good choice')
else:
await interaction.response.send_message("you're wrong")
you were using a class for the Select itself so you'd write
self.valuesinstead
self contains the actual object/instance, i.e. what stores the data
BRO I LOVE U
in my meau embed is there to make it edit no send a new message?
CODE -
await interaction.response.send_message(embed=embed)
@hushed galleon
huge progress today, but i kinda dont want to dive into more mechanics
but i shall perseverer
whats that
my trello board
i only have 3 must have features left
and a huge amount of things added already
What's that?
its a website that lets you make categories to put cards in, and lets you drag the cards between categories
it's pretty much like github project
in my meau embed is there to make it edit no send a new message?
CODE -
await interaction.response.send_message(embed=embed)
like a more intuitive github project
Cool
await client.currentEmbed[message.channel.id].edit(embed=embedVar)
you have to set the embed you sent as a variable, which you can then call on to edit later
What
What's client?
while True:
try:
user_input = "0+" + input("Equation: ").replace("^","**").replace("x","*").replace("X","*")
if any(c.isalpha() or c.isspace() for c in user_input):print("Not a valid equation")
else:y = "print(" + user_input + ")";exec(y)
except:print("ERROR - Stop breaking stuff")
in my code client is bot
client = commands.Bot(command_prefix="b|", test_guilds=[951923779859271711], intents=disnake.Intents.default())
Is currentEmbed a bot var?
currentEmbed is a variable under my bot
i just use markdown tables for charts like these 
it basically lets me carry around embed
You're doing client.currentEmbed so it's a bot variable
how can i get the line on the side of this embed?
i could do that but trello has pretty colors for covers and labels, a intuitive drag and drop system, and my teacher can see my progress
color=0x00ff00
in the Embed definition thing
constructor?
AttributeError: 'Bot' object has no attribute 'currentEmbed'
this
oh
that symbol, followed by a spacce then your text
or you could make an embed instead
it's already an embed katte 
@glacial echo do you know?
wait can you like explain a bit more?
What library are you using?
you have to define it as Bot.currentEmbed = none
> Hello
is
Hello
in the async?
async def callback(self, interaction: discord.Interaction, Bot.currentEmbed = none):
for example heres where i define all my bot variables
just use interaction.response.edit_message()
^
yes but i understand that but how would i use that on a embed
there are almost definitely several ways to edit the embed
cuz if i put > it wont work
you cant use markdown in an embed
so how did they add a line
in an embed it will already ahve a sidebar though
Show output
not the color line
what?
you can, but only in certain areas (descriptions, field values)
oh? interesting i thought you couldnt use it anywhere lol
the line near roster
Wrong reply sorry 
one more thing, anyone know how to only let the ctx.author be able to interact with the meau?
presumably, an if statement checking if interacter == ctx.author
this is what i get for randomly generating words from a library instead of making presets
that is color
yeah, but only if they have ctx
its just gray
File "main.py", line 94, in callback
if interacter == ctx.author:
NameError: name 'interacter' is not defined
interaction.user
add that or?
thats the > markdown in a desccription
replace that with interacter
ah sorry i was writing in sudo-code casue idk what the variables for intereactions are
did not work
show your code
class select(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='mod', description="moderation command's", emoji='π₯'),
discord.SelectOption(label='utility', description="utility command's", emoji='π©'),
discord.SelectOption(label='fun', description="fun command's", emoji='π¦'),
]
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, ctx, interaction: discord.Interaction):
if interaction.user == ctx.author:
print("ctx")
if self.values[0] == 'mod':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
command's isnt proper grammer
also last question how can i move the 19/30 to the side of roster?
idk why that wouldnt work other than that you cant have a ctx.author and a interaction.user possibly?
keep it on the same add_field line
if u send ur code that makes your embed it would eb helpful
i did
You gotta make ctx a class attribute
i did?
no
OH
how do i make it a attribute?
ik im not done yet
Pass ctx into the __init__ method, then do self.ctx = ctx. Then pass ctx into your select instance```py
select = select(ctx)
Hi people, I have a quick question.
Would this command be right to count the amount of members that are in the same server as my bot?
num_users = len(client.users)
print(num_users)
yes
Okay, thank you ^^
need to make bot premium subscription page ..what should i use never made one 
also last question how can i move the 19/30 to the side of roster?
new error
@boreal ravine TypeError: callback() missing 1 required positional argument: 'interaction'
It's not too important, when someone gets a second.
I tried to search it first.
I've tried in three different servers, it only returns 0 instead of counting members total.
I'm unsure of the issue or what's wrong, the bot is identified as client as well.
isnt members a privledged intent
?
Yeah, I forgot something, used a wrong variable somewhere.
Sorry, thanks for your help
it should be Guild.member_count
Yeah, I managed to get that lol
I just figured to ask because the CMD above is shorter and it was worth a shot lol
lol i need help
not if its a field
maybe if you do like ```py
**Roster:** `18/30`
```
this way its not its own field
show code
fix?
you need 2.0
how do i update
pip install -U git+https://github.com/Rapptz/discord.py iirc
tysm
HEY
OKIMIII

tryna help me w sum?
sure
class select(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
i want to allow only the ``ctx.author` to be able to edit with the UI
just pass the ctx author to the View subclass which you would use to add the author and then pass it to the select
class selectView(discord.ui.View):
def init(self):
super().init()
# Adds the dropdown to our view object.
self.add_item(select())
yes that one
class selectView(discord.ui.View):
def __init__(self):
super().__init__()
# Adds the dropdown to our view object.
self.add_item(select())
so
would i do if ctx.author:
if self.ctx.author != interaction.author:
iirc
lemme try
class selectView(discord.ui.View):
def __init__(self,ctx):
super().__init__()
if ctx.author != interaction.author:
self.add_item(select())
this?'
nah
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
here we would pass the author to the view where you add the dropdown which then it creates an instance of the parent class with the super and then it accesses the parents class init which then i passed the author to the dropdown which then you could add the if statement on callback.
oh, it says im missing a argerment but its not one?
did you passed the author when sending the view?
im pretty sure i did
code?
dont i need to add sum to my actually meau?
class select(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
@client.command()
async def test(ctx):
view = selectView()
await ctx.reply(view=view,mention_author = False)
you need to add an argument to the select class and you need to pass it to the instance of the view in the command
view = selectView() here you would pass the author as view is a variable thats literal to an instance of selectview
and class naming
okay so i add that to the veiw
ok now.
i wanna do wa

now wa
show code so i know were on the same page
can we use 2 python mysql database for 1 bot
nah iirc dpy needs 3.7+
:/
You can use 2 databases for 1 bot
um how?
Make 2 connections.
let me try
lmfao
oh wait he ment 2 different connectionsπ
im so sorryπ
excuse me
class select(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
@client.command()
async def test(ctx):
view = selectView()
await ctx.reply(view=view,mention_author = False)
Is there a example somewhere of what format discord likes embed JSON in? I had a poke around the docs related to embeds but couldn't find anything - and I mean discords docs
@slate swan
k
why are you making an instance of the dropdown in your view and you need to make an argument to the dropdown and you need to pass it in the command
!d discord.Embed.to_dict make an embed and just use this method and print it out.
to_dict()```
Converts this embed object into a dict.
OHHHH

what should i name agr
Thanks, seems like something discord could just add to their docs as a example, could have sworn I saw something like this about a year ago
are you really asking me what to name the argument
yeah u can pick
idk author is fine

do i do just author rn or author: discord.Member
shower brb ill be fast
as an argument yes
They do tough.
what one
an argument in the dropdown class
ik but author or the other one
Oh I've been looking for that, kinda expected it to be with the other embed docs like the limits
a new argument and not the view one
ok
then it will work?
Oh nvm this the js one.
not really as you still have to make the check in the callback
anyone??
Anyways to_dict will be it then. Also when making raw requests to the api the api usually sends a template for the devs.
you cant import it, you shouldnt import like that and you should use main or a fork
Good to know
i didnt import it
import discord, os, asyncio, json, sys, datetime, shelve
from discord.ext import commands
from discord_components import DiscordComponents, Button, Select, SelectOption, ButtonStyle, InteractionType
from discord.ext.commands.cooldowns import BucketType```
from discord_components import DiscordComponents, Button, Select, SelectOption, ButtonStyle, InteractionType whats that final import then
ssame3 error ahh

what import do i delet
i use it for my help menu for the buttoms
main has buttons.
do u have any source code?
for?
discord help menu with buttons
did you copy all of that code?
no offense but its honestly horrible
working doesnt mean good you know
send me a source help menu that uses main
alr
i assume you mean dropdowns https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
BACKK
class select(discord.ui.Select):
def __init__(self,author):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
@slate swan

anyone who can help w this error?
Ignoring exception in command nuke:
Traceback (most recent call last):
File "C:\Users\rebellion\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\rebellion\Desktop\chapter\cogs\betternuke.py", line 52, in nuke
await guild.create_role(random.choice(roles_spam))
TypeError: create_role() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\rebellion\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\rebellion\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 850, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\rebellion\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create_role() takes 1 positional argument but 2 were given
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
it doesnt take positional argument only self.
yeah normally it's name=...
but if i do that it says that the argument cant be done because i use random.choice
because i have multiple role names listed
make a variable thats bound to an instance of the class for the parameter and just on the callback add the if statement i gaved
huh
wdym?
send the if state ment?
no
^
and i add that to where
lemme read
the callback.
https://tokyotokyotokyotokyo.tokyo/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
https://tokyotokyotokyotokyo.tokyo/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
thats not how its done
Traceback (most recent call last):
File "main.py", line 2, in <module>
import discord
File "/home/runner/firelol-or-God/venv/lib/python3.8/site-packages/discord/__init__.py", line 20, in <module>
from .client import Client, AppInfo, ChannelPermissions
File "/home/runner/firelol-or-God/venv/lib/python3.8/site-packages/discord/client.py", line 38, in <module>
from .state import ConnectionState
File "/home/runner/firelol-or-God/venv/lib/python3.8/site-packages/discord/state.py", line 36, in <module>
from . import utils, compat
File "/home/runner/firelol-or-God/venv/lib/python3.8/site-packages/discord/compat.py", line 32
create_task = asyncio.async
^
SyntaxError: invalid syntax
yeah and when i remove the name= it doesnt give an error, only when i run it
name=random.choice(roles_spam)
is how you do it as the function returns a random string
you got discord or discord.py installed there m8?
oh
yeah i do
its just that repl screws a lot with the installation
ahhhhh
follow pep 8 bro
This error is given when you add asyncio
By that I mean the pypi one
If you're using 3.5+ asyncio is already in the stdlib
Throwback to the days
@slate swan wait, so i added the if statement, i have a argument error , even tho i added it??
where
missing 1 required positional argument: 'author'
well you need to pass it
i dont know how to pass , is there a thing i can read?
docs*

you pass the argument in the construction of the instance of the class
elif isinstance

IF
show code so i can guide you better
i legit js started using 2.0.0 td
class select(discord.ui.Select):
def __init__(self,author):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.ctx.author != interaction.author:
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
@client.command()
async def test(ctx):
view = selectView()
await ctx.reply(view=view,mention_author = False)
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
here delete the instance aka the view variable
embed2.add_field(name=f"**Roster:** {len(role.members)}/{cap}",value="" )
``` so when i run the bot it says to fill out the value but when it says to do that i do and it shows the what ever i put "" in it and how can i make it so it doesnt show what i put in ""
@client.command()
async def test(ctx):
view = selectView(ctx.author)
await ctx.reply(view=view,mention_author = False)
and here you would pass the argument as so
iirc you can just use bold space
** **
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
while True:
await channel.send(random.choice(message_spam))
how do i make this for text channels only?
so look, discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() takes 1 positional argument but 2 were given. this is a error im getting
Means the constructor method of selectView only takes self, you need to add another parameter to the constructor signature
how do ppl get the "add bot to server" thing on a bots profile
as far as i know u gotta enable it so everyone can invite the bot to their server in the dev portal
in general
anyone?
thats just screaming ratelimits
it's just to mess w my friends
idrc bout ratelimits
sometimes they annoying and i just wanna mess w em, we do it all the time to eachother
@slate swan
andy responded to you already and andy is kinda my teacher so he knows way more than meπ
I think this is the definition of api abuse.
dont know Β―_(γ)_/Β―
ohh oki
what should name be
i mean abusing the api to "just to mess w my friends" isnt quite right tbh
author?
its argument naming it doesnt matter
oki
if i get api banned it doesn't really matter for me. all i do is this anyway

Okay, but this doesn't really seem appropriate.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
well if y'all gon cry bout me messing w friends instead of helpin i'll just read docs
jesus christ
were not crying and shouldnt docs always be the first thing you check?
can i dm you rq
i cba to read that much.
no
oh
ok so, for i made it named author what do i do with it
i just had a question
ask here.
ok
We're not "crying" you are just abusing the API. Why should we condone this?
make an instance variable and check it with the if statement
in the actual command right?
the callback
okay
embed2.add_field(name=f"**Coach:** {message.author.mention} ``{message.author}``,value="** **")
this part of my code so when message.author.mention it goes in as a id since its in a ** but when i move my " back it shows a error @slate swan
you mean it doesnt format the mention?
yea
What code do you currently have?
cuzs my **
do you want me to send full code?
remove it then
no thats for the **coach**
Just the command and what you use/ call within it.
class select(discord.ui.Select):
def __init__(self,author):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='moderation', description="moderation commands", emoji=f'{emoji.mod}'),
discord.SelectOption(label='utility', description="utility commands", emoji=f'{emoji.util}'),
discord.SelectOption(label='fun', description="fun commands", emoji=f'{emoji.fun}'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder="categories", min_values=1, max_values=1, options=options)
async def callback(self,ctx, interaction: discord.Interaction):
if author != interaction.author:
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
@client.command()
async def test(ctx):
view = selectView(ctx.author)
await ctx.reply(view=view,mention_author = False)
oops
ah, can you even mention a member in the name of the field im not quite sure
yea
if you use value but you dont have to
you can just put it as in all one field
and your problem is that the name is bold?
yes and instead of mention it shows ids
because the bold of course
ah just remove the bold space and add something else
no that isnt effecting the mentions the ** coach** is
Well look at the selectView class, ```py
self.add_item(select())
view = selectView()

how would that affect it if its closed
lmao what can i get a tldr
its closed at the end π€£
idk can youπ³
and if i move it it gives error
yeah
how would i added author to pass?
embed2.add_field(name=f"**Coach:**"{message.author.mention} ``{message.author}``,value="** **")
^
SyntaxError: invalid syntax
ξΊ§
bro because it needs to be at the end of the kwarg bro

dawg thats what i do and it shows as a id
It seems you're missing a quote after the name=... kwarg
bro.
its an f string it doesnt do anything thats not how python or discord works
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
This wouldnt work i n main.py right
So when you call a class or a function you sometimes need to pass arguments.
def add(numb1, numb2):
return numb1 + numb2
print(add(4, 6)) # passing 4 and 6
>>> 10
``` if i were to remove 6 it would give me an error.
You literally used the service but then went out of your way to inconvenience yourself and others by screenshotting it anyway.
so what am i doing wrong
Oh no lmao its not my code someone elses and screenshotting seems more convenient to me
i think im not needed here anymore so ill be leaving
π
hm
what
what?
Huh?
do i need someones permission to leave
how with author tho
all i said was skull
whos
mans think i said stay or sum
mmhm k
@novel apex
well you replied with an odd emoji
class selectView(discord.ui.View):
def __init__(self, author: discord.Member) -> None:
super().__init__(author)
self.add_item(select())
view = selectView()
``` you are calling 2 things here but you aren't passing any args while they are required.
can u make a example using my problem ? @cloud dawn
yes, i removed veiw = selectVeiw()
You should be initialising an instance variable with it as well
Otherwise you won't have author in the instance
This chat never fails to confuse me
same here
I'm very much lost
are you talking about super().__init__(author)
No
hi i'm trying to make a discord bot, completely new to all of this, and would really appreciate some help. i followed a tutorial to set up the basic basic basics on replit and i have an idea of what i want to make but no idea how to go about even starting. i want to convert user input to an image output, do i have to use matplotlib for this? cause i've never used that before either n i'm just really overwhelmed by everything
i think everyone here is not on the same page
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@slate swan I highly recommend taking a look at what okimii sended https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
i have a lot of questions and i see you guys are busy with something so if anyone just wants to dm that would be much appreciated
yeah
What do you mean by "image output"?
Are you planning on querying for an image?
anyways bye guys
So basically user input that searched images on google?
do you even know what im trying to get ?? @cloud dawn
there's a texit bot that people use to make math equations and change up text, something similar to that
i do not know what this means lmao
Seems to me like a help command.
no it converts what they input into an image with that text written in it
yeah, but i only want the ctx.author to be able to edit the interaction
i think u would use pillow for that
Ah pillow pypi
i have heard of that one! how?
@pastel flint on youtube there is some thins look up pillow discord bot
alright i'll watch a few, thank you!
@cloud dawn
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
How can i fix this i tried moving it up but it messed with my mention
I'd have to debug it and i can't rn.
Well the format isn't in the string.
wdym
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Look at this
wait
You got f"some text"{format??}
so what i am saying is that when i put the " at the end it messes with my mention and puts it as a id

bro idk what to do i give up
Never give up, anyways i'd need to program myself to clearly give a good example since the internet doesn't have one apparently lol
i dont understand what , what ur saying im really not that good at understanding py
hi i'm back i watched two videos and neither are very helpful for the context of making a bot
what was the youtuber's name?
Regardless most youtube discordpy tutorials suck
yeah kinda
Corey Schafer and dannycademy
let me send u the one i used.
yeah i really just need someone to dumb this down to the level of a baby
Lucas incoming
so u want a command like
?image hello
and hello will be on the image?
freecodecamp has joined the chat
Are you just going to spoonfeed commands?
Anyone able to help with this by chance?
I'm wanting to post an emoji in a description embed.
I figured you just copy the ID by putting \ is there another way?
π°
In this video, we will be adding text in Images with Pillow. We also make an image command using discord.py (rewrite) in 2020.
If you have any suggestions for future videos, leave it in the comments below.
Some Useful Links -
Discord Developer Portal- https://discord.com/developers
My Discord Server- https://discord.gg/TXF3hBj
My Twitte...
okay well i want to make the output a punnett square
so the user would type something like .pun Aa AA
so each character would need to be printed in a different place as well as combinations of them
as well as a chart
and ideally it can work for traits up to any length so the input could be .pun AaBbCC AAbbcc or etc etc
or sorry dihybrid crosses would be like AbaBABab, ignore what i just said
it would be easiest to start off with a simple 2x2 lmao
There is quite a lot of steps here
Personally, I'd start off by determining dominate vs recessive alleles and storing them into a variable
You can check using str.isupper() since dominate alleles always have to be capitalised
i'm going to ask this once is py better than js?
alleles?
then you can either use control-flow, so using else to determine recessive alleles, you may also use str.islower()
Neither is better
{
"name":"Jack",
"age":30,
"address":{
"street":"Station Road",
"city":"London"
},
Then all you'd need to do is render the text using Pillow
They're used for different things
how to write like this in json file with python
alleles are the "a" or "A" that makeup the trait
okay thank you so much
Sounds like a good idea could be helpful as well
@cloud dawn i give up , im going to take it off what to i remove again
tbh not even going to try to understand
Perhaps a fun adding would be x-linked traits support
how do i store them as separate variables if the input is all together?
oh i have such an ambitious project idea that i have no clue how to make
Did you miss the colon πΏ
Well, there is many ways you could do this ```py
dominant: list[str] = []
recessive: list[str] = []
for char in foo:
if char.isupper():
dominant.append(char)
elif char.islower():
recessive.append(char)
Alternatively you could use regular expressions
But I find simple iteration like this to be quite easy
code - ```py
async def callback(self,ctx, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
error - ```py
TypeError: callback() missing 1 required positional argument: 'interaction'
If anyone can help, I am using nextcord and am unsure how to post an emoji in the description of an embed.
Emoji ID: (Correct)
I checked around and can't seem to figure it out, posting it as is doesn't seem to work
that makes a lot of sense, thank you. my question now is how do i get the user input into the foo list? if they type .pun AA aa, how do i check the message for the bot to respond to and store variable input in the same line? or would i have to have the bot initiate another prompt like enter parent 1 and 2? if so, how would i do that?
if I'm correct the correct format for animated emojis is <a:name:id>
Which, that's just by typing \ in front, right?
yeah
embed = nextcord.Embed(description="emoji_thing") like this?
discord autocorrected it π
Well, you're working with two arguments, so your callback signature should look like py async def command(ctx: commands.Context, first: str, second: str) -> None: , .pun AA aa would then store AA in first, and aa in second. Alternatively, if you want to use , like in your example. You could do ```py
async def command(ctx: commands.Context, alleles: str) -> None:
foo = alleles.split(",")
foo would then become a list using , as the split char
!e ```py
print("foo, bar".split(","))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
['foo', ' bar']
Just make sure to cleanup the spaces
hey andy, im having a error
thank you! lemme try this out
Yes, though, it ends with
description=f"... ... {latency} "
Then when I get it posted, it shows as the image
async def callback(self,ctx, interaction: discord.Interaction):
if self.values[0] == 'moderation':
embed=discord.Embed(description="moderation")
embed.set_author(name="")
await interaction.response.edit_message(embed=embed)
else:
await interaction.response.send_message("you're wrong")
this is code and my error im getting is TypeError: callback() missing 1 required positional argument: 'interaction'
π
doesnβt work
- why pass
ctxif it isn't used - can you send full traceback
is the error on the line of the function signature?
Do you mind if I message you the code and you can try it yourself?
thsure
wait is it even possible to use pillow for python on replit
@pliant gulch i think i might try making this as a regular program before implementing it as a bot, retreating back to VS. thank you for your help, i will probably come back with more questions lol
callbacks don't give you ctx
how so?
in really simple terms, what is ctx
Context for the invocation
Short for contex, it gives info such as the user who ran command, channel, guild, command object, etc
It's basically a discord.Message instance, but adds information regarding to command, command invoker, etc
ohhhh cool thank you
Without it you wouldn't really be able to get that info
are you sure the bot is in the server where the emoji is in?
That was the reason ^^
Figured it out a min ago lol
lol
also another question @pliant gulch, earlier when you typed the example you ended the line with "-> None:". what does that do?
Typehints the return of a function
typehints?
ah i think i am
mostly documentation purposes
Basically a function that says, "Hey, I won't actually return something but i'll do a side effect"
If you don't typehint much you don't really need to worry about it
Basically just self documenting code
Yeah as CokeCane mentioned, python itself doesn't care about it but it's useful for your IDE that can provide you methods and attributes using autocomplete
ahh okay
Many dynamically typed languages have some form of typehinting because knowing the type of a variable is important
i giggle a little bit whenever robin says my username
What do you want me to refer to you by π
same
CokeCane
Well in that case
π
I wouldn't mind humoring you π
same
Still waiting on generic tuples to get passed, for now I'll have to use typing_extensions
TypeGuard is also very very nice
in that CamelCase
buttons for dpy 2.0.0
can someone send docs
link buttons ^
i dont se link buttons
have anyone use hikari before?
so how do i fix
code - ```py
@client.command(aliases=["av"]) # i will be adding this
async def avatar(ctx, *, member: discord.Member=None):
if member is None:
member = ctx.author # ok wait im gonna do 2 and you cacn pick
req = await client.http.request(discord.http.Route("GET", f"/users/{member.id}"))
avatar_id = req["avatar"]
embed=discord.Embed(color=color.color, description=f"{member.name}'s avatar\n png , jpg")
embed.set_image(url = member.avatar)
await ctx.reply(embed=embed, mention_author=False , components=[Button(style=ButtonStyle.URL, label=".png", url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024")], components2=[Button(style=ButtonStyle.URL, label=".jpg", url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024")])
saying buttons wont work?
import discord
from discord.ext import commands
from itertools import cycle
import asyncio
from custom import color , emoji
from discord import Intents
import aiohttp
import bs4 , io
imports
You're supposed to pass in a discord.ui.View object
Something like so:
class MyView(discord.ui.View):
...
@bot.command()
async def my_command(ctx: commands.Context, ...):
view = MyView(...)
await ctx.send(view=view, ...)
do i have 2?
Also you can just get a member's avatar url by using member.avatar.url
not need to specify it manually
Yes, you do
thats so dumb
I guess you can also use .add_item() but you'd have to subclass that as well to get a callback
How so? It's quite easy
wait can i just copy and past
components=[Button(style=ButtonStyle.URL, label=".png", url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024")], components2=[Button(style=ButtonStyle.URL, label=".jpg", url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024")])
No you won't be learning anything from that
ik but so i know
https://github.com/Rapptz/discord.py/tree/master/examples/views take a look at this for examples
yeah it is
https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py take a look at this
They subclass view here but you don't need to
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
caan i use await?
@sick birch
then when i switch them around this happens
discord.ext.commands.errors.MissingRequiredArgument: self is a required argument that is missing.
@sick birch
youre missing the self argument to access an instance of the class
Can you send your code?
i got off lol.
i didnβt get any replyβs
lemme send it
why're you making requests
iβll fix that
@client.command(aliases=["av"]) # i will be adding this
async def avatar(self,ctx, member: discord.Member=None):
if member is None:
member = ctx.author # ok wait im gonna do 2 and you cacn pick
req = await client.http.request(discord.http.Route("GET", f"/users/{member.id}"))
avatar_id = req["avatar"]
embed=discord.Embed(color=color.color, description=f"`{member.name}'s avatar`\n [png](https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024) , [jpg](https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024)")
embed.set_image(url = member.avatar)
await ctx.reply(embed=embed, mention_author=False)
self.add_item(discord.ui.Button(label='png', url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024"))
self.add_item(discord.ui.Button(label='jpg', url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024"))
@sick birch
why do you have self in the commands parameters
for self.add_item
it doesn't work like that
useless f statement you can just do member =member or ctx.author
so do i even need self?
is it in a cog?
no
@client.listen('on_raw_reaction_add')
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
print('test')
if payload.message_id == 958024371115548772:
guild = client.get_guild(payload.guild_id)
if str(payload.emoji) in 'πΌ':
category_channel = guild.get_channel(956572065660547104) # pass in category channel id here
await guild.create_text_channel(name='channel_name', category=category_channel)
await payload.message.channel.send('Created a ticket by {user.author}!')
its creating the channel but not sending the msg on that channel
you do know self is only for accessing a class instance right?
oh the other guy is said to put that
now itβs sending the embeds but not adding the buttons @slate swan
!self
Class instance
When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.
Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').
Why is this useful?
Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.
Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.
he also said bc itβs a link button i can have it in the command
itβs just a link button
The payload.message might be partial also do you have an error handler
Try getting the channel with payload.channel_id
can you rewrite ? i am not understanding
await guild.get_channel(payload.channel_id).send(f"Created a ticket by {user}!")```
Also not sure if your user is defined
oh no it isnt
where can i define it? sorry i am new in dc.py
Either by client.get_user(), guild.get_user() or guild.get_member()
See docs
how to make inventory command using sqlite database
You need db structure suggestion or something
Cause nobody will give you complete solution
you have to first design your database table.. like the columns, rows etc... then insert the data then fetch it... if you want more help with databases, #databases is the right channel
so when i use vsc
it opens sqlite database
but when i run on python
it says cant open database sqlite3 operational error
Is there anyway for the bot to play the next song automatically
@bot.command(pass_context=True)
async def play(ctx, url=""):
global voice2
voice2 = ctx.voice_client
queue.append(str(url))
i = 0
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {
'format':"bestaudio"
}
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(queue[i], download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
voice2.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
del(queue[0])```
Heres my code
I created a list name queue to store the song's url
!ytdl we will not help with projects that break YouTube's ToS
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)
Oh sorry I didnt know that yt_dl breaks the youtube tos
Are there other libraries that can are comply with yt tos
Not really, any automated way of downloading videos are not allowed
I see, thanks
from discord.ext import commands
import os
import discord
client=commands.Bot(command_prefix='.')
@client.event
async def on_ready():
print('ready')
@client.command()
async def kick(ctx,person:discord.Member):
await person.kick()
client.run(os.environ['Token'])
when i run this command,i am getting this error
Traceback (most recent call last):
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 10, in kick
await person.kick()
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/member.py", line 568, in kick
await self.guild.kick(self, reason=reason)
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/guild.py", line 1997, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Moderator-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
although i gave my bot the administrator perms
Does the bot not have the kick_members permission? Are you trying to kick the owner of the guild?
Well, then, it's probably the latter, or the bot's highest role is ranked lower than / equal to the highest role of the target user
A discord server
i am just trying to kick another bot
oh
Are their highest roles the same one
Like Bot role or something
i think
That's probably it
oh thx
im using replit, what am i
a brainless developer
lol
How does the stuff inside on_disconnect event works when bot is disconnected? ping me when u reply
idek that existed
That exists
In pycord as well as discordpy
At least.. idk about other libs
i have no idea how that works
Ping me if u know the answer
sryy
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_connect "discord.on_connect") call.
I mean
Ik I saw that
But
How is bot able to send the content when it's already disconnected?
It doesn't make sense to me.. like how is the application working when it has lost connection
I hope u getting my point π
Aahhh bro
Ima DM u one pic ..
Dw I won't bother u in DM
Just look at thay pic and we will continue the convo here
@slate swan ok so there I'm using on_reconnect and disconnect thing
Like it make sense about disconnected
I mean reconnect
But that disconnect shut.. not making sense to me..I had this shit working for days.. and I got this doubt today when my djs friend asked me about this thing
ππ
Sorry I'm on mobile.. so sending screenshot.. pls Cooperate
Yehhh
How can you send a message when you are disconnected
ππthat's what I'm asking
That shit is working lmfao
Does bot class have any methods that state if the bot is connected
Well.. for now I'll go with this
Sending message is done with single API request
But I've dropped same question in other servers
Receiving events is done with websockets
Will see their explanation
API can't be disconnected but websockets can
When bot is disconnected, it can't receive events but can send API requests
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
I think that
π€π€
When internet is lost.. why api can't ve disconnectedπ
Yee
Well alr then
Thanks for being bothered by meπ
Have a good day! Lmao
Send message requests just go to this endpoint https://discord.com/developers/docs/resources/channel#create-message
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
from nextcord_buttons_plugin import *
ModuleNotFoundError: No module named 'nextcord_buttons_plugin'
guys help
nvm
how to solve this error
async def register(ctx):
registerr = "INSERT INTO usersdata (userid, balance, tag) VALUES (%s, %s, %s)"
val = (ctx.author.id, "1000", "JOBBER")
cur.execute(registerr, val)
mydb.commit()
with open("data.json", 'r') as f:
users = json.load(f)
users[str(ctx.author.id)]["auracoin"] = 1000
with open("data.json", "w") as f:
json.dump(users, f)
await ctx.channel.send(f"{ctx.author.mention} SUCCESSFULLLY CREATED YOUR ACCOUNT")
here is my code
wait... wait.. you tryna use json as db? π
nah nah
aah that json.dump shit scared me to think that you're using json for db
i m using mysql as db
so what i have to change
uhmm see
show
wel can ya vc? i'm lazy to text
i m not good in english :/

