#discord-bots
1 messages Β· Page 1065 of 1
update one means not all of them
π I think I will just clear everything and then send the info to the db again, since this will kill all my braincells
i'd recommend you restructure your data
I wouldn't do that. updating is the best way to do it
And what should be the updated struct?
mongo's lack of structure lets you start stuff like this, and then it'll get frustrating
Just have different columns for each piece of info you would need for each user
something like {"_id": <user id>, ... rest of the data}
doing this lets you filter for a specific user's data, which wouldn't be possible if the key itself is the user ID
Ah, so u mean a separate table for each user?
no
a separate document
Just separate rows for each user
and each user would have multiple columns to store their data
rows and tables are SQL lingo
Ah
O
(and columns)
Oh
the mongo analogue to an SQL table would be a collection
Wait did u set the _id by yourself?
This is one of my documents for example, just has an id and then all of the info
and each collection would contain many documents (rows)
I did that so I could match their ID's with their discord ID's
But that is not something you have to do, you can keep it default
yeah mongo automatically sets one if you don't specify, but you can set your own ID too
I thought Mongo set the _id itself lol
That will make stuff easy tho, no? If I set the ID to user id
yes, that's what i suggested
just pass an _id field when you're inserting the data
Gotcha
insert_one({"_id": user.id})
Thanks
oh also, i'd suggest trying out prisma-client-py, it's a fully type-safe ORM with support for mongo as well
Oh thanks!
guys do you know any resources on what to pay attention for if you want your bot to grow big (many guilds)?
like command cooldown etc
Error handling
Unique command choice
Also what I learnt from making a verified bot, u should always test out with cooldown times. So that, it is neither too long neither too short and also gets the work done
i mean like limit 50 websocket commands per second
that's 1 message per second for 50 guilds
Well what ws commands r u letting the users run?
none
i mean bot communicates through websocket. channel.send() is 1 websocket command
really?
Yes
ok i know nothing π
Its fine haha
its bot.http.create_message(channel_id, *kwarg)
for the request sending parts, yes
but it uses gateway so requires websocket for the events
That is what every API wrapper is
Its just an easier interface between yr code and an API, the Discord API, in this case
@slate swan do u know of any dunder which is called whenever I do dict(classA) or smth?
not that im aware of, lemme see
Thanks
__iter__ gets called, im unsure if its only that dunder that gets called
!e ```py
class MyClass:
def iter(self):
return iter([("key","value")])
print(dict(MyClass()))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
{'key': 'value'}
there may be more dunders~
A dictionary or other mapping object used to store an objectβs (writable) attributes.
Il need some help probs tommorrow or so or later on today
Hey @abstract kindle sorry for the ping but this code doesn't seem to work:
async def update_db():
ai_session = ai
session = ai_session.db
users = ai_session.get_all_info()
num = 0
for user in users:
num += 1
my_user = AIUser({"_id": "1", "name": "Hun", "iter": str(num)})
await session.update_one({"_id": str(user)}, {"$set": dict([*my_user])})
Wait nvm seems like my code issue
Wdym lol
How to send a message.content without the first letter?
If someone said NBob
Bot would respond with Bob
Doesn't mongo set the _id field itself
Oh nevermind it's an update
What's wrong with this code?
It's not sending errors and not sending the message on join
class MyClient(discord.Client):
async def on_ready(self):
print("Bot running with:")
print("Username: ", client.user.name)
print("User ID: ", client.user.id)
print('-----')
async def on_message(self, message, interaction):
# To prevent the bot replying to itself
if message.author.id == self.user.id:
return
if message.content.startswith('N') and discord.ChannelType.private:
await self.interaction.response.send_message(f'Nickname set to{message.content[1]}')
async def on_member_join(self, member):
view = Introduction()
await self.member.send(f'Welcome to the server {member.mention}! Use the button below to make an introduction and get access to the server.', view=view)
@commands.guild_only()``` guys what does this mean?
maybe commands that are only useable inside a guild(can't use them in private chat/direct messages)
bruh
idc ima just use @commands.command()
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a
guild context only. Basically, no private messages are allowed when
using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage")
that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@warped mirage
if i usethat will it stil work for multi guild
It will work only in guilds
Yea
Does archive fall under on_thread_update?
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to
do this.
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
np
won't discord.error.Forbidden be raised when bot not user has no ban permission?
content[1:]
Ty
you have use it wrong
Yea ik
discord.ChannelType.private will always be true
I forgot
oh wait what
how should I do it
you want message.channel.type == discord.ChannelType.private
ok ty
Forbidden inherits from HTTPException, MissingPermission inherits from CheckFailure, which inherits from CommandError which inherits from DiscordException
async def on_message(self, message):
# To prevent the bot replying to itself
channel = message.channel
if message.author.id == self.user.id:
return
if message.content.startswith('N') and message.channel.type == discord.ChannelType.private:
await channel.send(f'Nickname set to **{message.content[1:]}**')
await message.author.edit(nick=message.content[1:])
How can I set user nickname to message content
You will need a Member object to use edit()
`β
you need a member object
ic
!d disnake.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timeout=..., 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...
since members are specific to guilds
\β
user is just any discord user
wdym?
hmm
@commands.guild_only()
async def giveaway(self, ctx):
await ctx.send("Lets Start this giveaway, answer the questions I ask and we can proceed.")
questionList =[
["What channel should it be in?", "Mention the channel"],
["How long should this giveaway last?", "d|h|m|s"],
["What are you giving away?", "E.G. Pizza"]
]
answers = {}
for i, question in enumerate(questionList):
answer = await GetMessage(self.client, ctx, question[0], question[1])
if not answer:
await ctx.send("You failed to answer, please answer quicker next time!")
return
answers[1] = answer
embed = discord.Embed(name="Giveaway Content")
for key, value in answers.time():
embed.add_field(name=f"Question: `{questionList[key][0]}`", value=f"Answer: `{value}`", inline=False)
m = await ctx.send("Are all these valid?", embed=embed)
await m.add_reaction("β
")
await m.add_reaction("β") ``` GetMessage is not defined , how do i fix
!d disnake.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
what's disnake is that a library
d.py fork
just use discord instead
!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...
that's a bad idea
you mean variable right?
this is a little advanced
"how do i break into houses of people that bought my tv?"
member = message.author
since there isn't a method to find the guild invite from a guild, you can only get all active invites from a guild
no?
ok
say i have a private server and i use your bot, suddenly owner appears on my server
hmm wait
Okay so I forgot, but the tasks.loop's first iteration is done as soon as the bot starts or after the time I specified in the deco?
!d disnake.Guild
class disnake.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI...
as the bot starts
Rip
i don't remember the workaround to fix this sadly
Oof
wait i remembered that i've sold a bot which does something with tasks
Ouh
how do you want to delay it? by a time or when the bot is ready?
something really stupid lol
you use @task_name.before_loop decorator
Suppose if the task is set to iterate every 10 min, I want to make it so that the first iteration is done after 10 min
class MainLoop(Cog):
def __init__(self, bot):
self.bot = bot
self.check_news.start()
self.first_launch = 0
@loop(minutes=40)
async def check_news(self):
if self.first_launch == 0:
self.first_launch += 1
return
#your stuff
What the
How can I change message author's nickname
so just:
@task_name.before_loop
async def wait_some_time(self):
asyncio.sleep(60 * 10)
I told ya that it was a workaround 
hm good idea
It doesn't work
thats the only option lol
i wish there was smth like before_first_iter lol
When I try and use the command, it doesn't respond back
import discord
from discord.ext import commands
intents = discord.Intents()
intents.guilds = True
intents.guild_messages = True
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.command()
async def pdc(ctx):
await ctx.reply('is awesome', mention_author=True)
bot.run('REMOVED')
ctx.send
Wait, what if I start the task after 10 min
I tried that too
maybe use a command
before_loop and before_first_iter mean the same thing, just that the function names are different
before_loop is exeucted before ever iteration
nope
this will start the task after that time, so after 10 minutes it will wait another 10 minutes before starting the loop 
No
@bot.command()
async def nickname(ctx: commands.Context, *, nick: str):
await ctx.author.edit(nick = nick)
await ctx.channel.send(fβ{ctx.author.mention}βs nickname set to {nick}β)
or something
im on mobile so i may have made a mistake
it never says restart
Yea I just remembered u r correct
||Fuck this shit ||
eh
try the discord version maybe
!d discord.ext.tasks.Loop.before_loop
@before_loop```
A decorator that registers a coroutine to be called before the loop starts running.
This is useful if you want to wait for some bot state before the loop starts,
such as [`discord.Client.wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready").
The coroutine must take no arguments (except `self` in a class context)...
...
so as i said, the coroutine is called before the loop starts
so if you wait 10 minutes in the before, then the loop starts and waits another 10 minutes
no its just sitting on my pc
majority of people let it stay open and go on to do something else
lol
lmao
Ik lmao
I do it too sometimes 
who doesnt like it when people think youβve been coding for hours πΆβπ«οΈ
bro, the loop's first iter happens as soon as the bot starts, so if I am waiting for 10 min before first iter, it will start after 10 min, the first iter
Like i use pycharm for work but i'd open it but never close it
This is so confusing
weird, I always disable my discord presence extension when I have long hours of work ;-;
Why a loop could not start after the time lol
Lmao no one likes to disable their presence and show off that they are working since hours @slate swan
And, well I prefer to turn off my laptop so that no one edits my code
I don't so people thinks that i'm working and i've an execuse to not reply them 
dunno I just find it weird when I have vsc open for like 5-6 hours and my friends (i dont have them but okay) start messaging me about what I'm doing on vsc, so I just find it weird π
lol I was kidding
Lmao no one really cares if I am working on VSC or smth
can we switch living environments
lmao
class Life:
def __init__(self, people: 'People'):
self.people = people
def switch(self, with_: 'People'):
tmp: 'People' = with_
with_ = self
self = tmp
class People:
def __init__(self, name):
self.name = name
Ash = People("Ashley")
Hunt = People("Hunter")
AshLife = Life(Ash)
HuntLife = Life(Hunt)
AshLife.switch(HuntLife)
smth like this, let's develop it
you alright?
Yeah i'm hungry and i've started my daily work call so 
Lol that's something i've done in C
The universe is trying to tell me something
get_human(name="BlvckTvrsier").feed(food.Pizza)
Are you accusing me of being italian? because yes, I am 
italian language is cool π but i failed to learn it to the conversational level
Bruh listen an Iitalian, italian is not cool lmao
lol
also only few italians speak it correctly
Bruh why Chrome icon has a box on my desktop 
class uwuClient(Client):
def __init__(self):
self.boot_time = round(datetime.utcnow().timestamp())
client = uwuClient()
@tasks.loop(seconds=10)
async def uwu_loop():
print(round(datetime.utcnow().timestamp()) - client.boot_time)
@uwu_loop.before_loop
async def _():
await sleep(10)
@placid skiff this is why it only waits before the first iter
sorry for even thinking about it :>
.....ooof sorry
Yeah meanwhile i found why in the source code it starts without waiting the time 
no comments
Who wants to create a fork to subclass Loop class and make a method that waits the time before execute the function? 
a fork for just task manipulation?
better create a separate api wrapper
wait = True
@loop(...)
async def foo():
if wait:
await sleep(10)
wait = False
# stuff
``` L
i forgot to global it^
bye
lol
meanwhile the discord.py server:
Bruh literally here we are doing a job
no
we tend to confuse a small amount of people by coming up with all sorts of problems they have with their code rather than helping with what they came for, which frustrates other people and they lose interest, and subsequently ask their questions in the discord.py server. Period.

Why doesn't my bot reply when I run the "$test" command?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$', intents=discord.Intents.default())
@bot.event
async def on_ready():
print('Successfully logged into {0.user}'.format(bot))
@bot.command()
async def test(ctx):
await ctx.send('hello')
bot.run(TOKEN)
Bot has administrator perms in server
how do i change guild vanity code
discord.py version?
if it is 2.0, enable the message content intents
Ok, Iβll try that
You can't
why
Because there isn't a method to do it 
duh if one could do it with api caller why not with dsicord py
They would've their reasons, btw if you want you will need to do it by APIs too
yup it gets the url code, but you can't edit it
it returns a string, it is not even a discord object
!d discord.Guild.vanity_invite
await vanity_invite()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the guildβs special vanity invite.
The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features "discord.Guild.features").
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use
this as well.
this returns an Invite object
.....
try to change it with what this methods will return
i just want the vanity code from it
how to derive it
vanity_invite.code()?
vanity_url_code?
If you have an invite object
but it is an attribute, and it will just get you the vanity code
Guild.edit() takes vanity_code as its keyword argument where you can use it to change the guild's vanity url code.
wont work, you can only delete invites
,.
dumb question but, whats a vanity url code......
It is something that you will get when your guild reaches the max level of boosting
and just fyi, even the discord api restricts the editing of vanity urls
hm weird
then you can have a personal invite link like discord.gg/myserver
I know that
thanks though
and the discord api only allows the getting of the url
oh ooooooooooof, just refer to it as an endpoint for the server invite
referring to that as the code right?
Yup
pfftt
btw it has some limitations
like the person who access the guild through that link will be redirect to the first visible channel in list for his role
seems quite right
Your imports?
from discord.ext import commands
import aiohttp
import asyncio
loop is located in discord.ext.tasks.loop
How can we download discord.py 2.0? Using pip
you will need git
^, pip install git+link
Ok
pip install git+https://github.com/Rapptz/discord.py
Why does my python bot keeps sending messages when I sent message that isn't even contains in message.content.lower?
#chat bot
@client.event
async def on_message(message):
if message.author == client.user:
return
if 'hello' in message.content.lower():
await message.channel.send(random.choice(greetings))
time.sleep(1)
await message.channel.send(random.choice(cq))
thanks
This is what happened:
Weird asf
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\prefix.py", line 20, in change_prefix
db.execute("UPDATE guilds SET Prefix = ? WHERE GuildID = ?",
AttributeError: module 'db.db' has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\events.py", line 61, in on_command_error
raise error
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'db.db' has no attribute 'execute'```
is my code correct?
Do you mean why it sends 2 messages? Because you have 2 .send() methods in your code.
because the bot is replying to itself
No.
#chat bot
@client.event
async def on_message(message):
if message.author == client.user:
return
elif 'hello' in message.content.lower():
await message.channel.send(random.choice(greetings))
time.sleep(1)
await message.channel.send(random.choice(cq))
why use elif?
because you only want the trigger to work if the first statement is false
elif runs if the previous if/elif statement evals to false
if both are ifs then its gonna run either way
^
"if" works, no need "elif"
it will automatically update, or do u want to make code for updating member count in bot status?
I dont think that will cause an error though
I got it
its not causing an error
its just that the bot replies to itself
!e
from asyncio import get_event_loop
em = True
async def main():
if not em:
return
elif em:
print("uwu")
get_event_loop().run_until_complete(main())
like its gonna work ofc
lmao
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:9: DeprecationWarning: There is no current event loop
002 | uwu
hmm
!e
name = 10
if name > 9:
print(1)
elif name > 8:
print(2)
@regal pulsar :white_check_mark: Your eval job has completed with return code 0.
1
its not going it print 2
since the first if already evaled to true
on the other hand
!e
name = 10
if name > 9:
print(1)
if name > 8:
print(2)
@regal pulsar :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
yeah he didnt have elif before
it's a different case if you put the return keyword, it will just quit the function instantly.
hmm
oh oops
!e
name = 10
def main(name):
if name > 9:
return
elif name > 8:
print(2)
main(name)
@regal pulsar :warning: Your eval job has completed with return code 0.
[No output]
how do i fix this
hi im having a issue i have this piece of code
response = requests.get(f"https://valorant-api.com/v1/agents")
json_data = json.loads(response.text)
print(json_data)
this returns all agents but if i just want sova how would i do this ?
read their documentation, easy
i did that but i couldnt find it
use this - https://valorant-api.com/v1/agents/320b2a48-4d9b-a075-30f1-1f93a9b638fa
this will return the data for sova
You are so kind Ash you searched through the docs for him
how do you get the data ? cause i want to be able to do !valoagent sova and get sova ?
actually, the valorant api is unofficial and asked for the agent Uuid which they didnt specify anywhere
use a dictionary, with the Uuids and get the keys?
oh okey thanks for helping !
https://gist.github.com/NotOfficer/8da2e088a596bc6acc1b46b4c2d0c64b here's the list of Uuids
a simple use case could be
c = {
"sova": "Uuid"
}
c.get("sova")
like that
i would never have come up with a dictionairy method
dont want to imagine the conditional tree

Revealing area
nvm
thanks
πππ
you saw?

uh?
:D
...show what? dont be so happy
what is what?
:/
Oh don't worry is nothing to be worried about
Does thread.owner_id refer to the person who created the thread or the owner of the server?
the owner of the thread 
Misunderstood πππ
Its my id :/
Um, huh?
The person that open the thread
Right. Thanks
Yo what ? - MessageContentPrefixWarning: Message Content intent is not enabled and a prefix is configured.
I've enabled message content from devs portal
Go to discord dev portal
What about bot=
you need to enable disnake.Intents.message_content
Thanks, it's a new thing now?
disnake has shifted to v10 already?
well it was released like a month ago 
Bruh disnake updates in 24h after a discord update if it has some impact on the API
weird
Just efficiency
What was going on with rate limits yesterday?
Like a lot of people were experiencing it
Which people?
People from Discord Developers server
Replit pepo
NAA
πππ
no replit
You know, people who don't read TOS
Lol
Dude, it was later on fixed xd
It happens to everyone
imagine not reading the TOS every app you use
Well of course i don't read everything and i don't read every TOS
Lol
xD
Me who NVR reads that boring essay
Me who reads TOS only when something bad is happening to me
Lol
I'm pretty confident 
Once you've read one terms of service you typically only need to skim new ones
The majority of a ToS is ass covering and "dont use our platform for malicious or illegal stuff"
yeah essentially that's what it is
Fortunally discord ToS is divided in section 
There is a section reserved to iOS user only
Cuz they had to specify everything that they've specified before in the ToS but with the word "Apple" before everything 
Since ios users couldnt behave
π
How can i make a bot that send private message to everyone?
let's talk about this clause in the AWS terms of service
However, this restriction will not apply in the event of the occurrence (certified by the United States Centers for Disease Control or successor body) of a widespread viral infection transmitted via bites or contact with bodily fluids that causes human corpses to reanimate and seek to consume living human flesh, blood, brain or nerve tissue and is likely to result in the fall of organized civilization.

basically "There restrictions don't apply in a zombie apocalypse"
!d discord.Client.users
property users```
Returns a list of all the users the bot can see.
If you send DMs to everyone your bot will be quarantined from sending DMs, in general, do not mass DM users
Only that bot right do it doesnt matter
Ill just create another
||btw this is one of the classic question I read before reading "WHY MY BOT IS NOT WORKING IT WORKED YESTERDAY" (yes is the question before get rate limited)||
Uhm no
they rate limit your ip 
You still shouldnt mass DM even if you can just use another bot when it gets banned because it's a scummy thing to do
Heyo, how do I access the page attribute here?
class PetPaginatorButtons(discord.ui.View):
def __init__(self, page, *, timeout=180):
super().__init__(timeout=timeout)
self.page = page
in this decorator?
@discord.ui.button(label=, emoji=self.page.emoji, style=discord.ButtonStyle.green,
disabled=not pages[0].can_buy, custom_id="purchase")
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object BanIterator can't be used in 'await' expression
@client.command(aliases=["unbanall"])
@commands.cooldown(1,5, commands.BucketType.user)
async def unbanalll(ctx):
guild = ctx.guild
banlist = await guild.bans()
v = embed = disnake.Embed(title='Alpha. ', color=0x2f3136, description=f'**Unbanning {len(banlist)} Clients**')
g = await ctx.send(embed = v)
for users in banlist:
await ctx.guild.unban(user=users.user)
await g.delete()
await ctx.send(embed = disnake.Embed(title='Alpha. ', color=0x2f3136, description=f'**Done!!**'))```
how to solve this error
huh
I want the label in my error to be self.page.label and the emoji to be self.page.emoji but I don't know how to access the page that the view is currently on
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission
to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list...
the error is speaking too 
how to fix
it is written in the docs 
any shot you can check my question
π«
i dont uderstand i tried it too and getting the same error
bruh it it written Retrieves an async iterator you are trying to use it like an async method
i tried it too
stil not working and this was working some days ago
it?
it is just bans = Guild.bans(**kwargs)
then bans is equals to an async iterator
so you will have to do an async for
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\prefix.py", line 20, in change_prefix
db.execute("UPDATE guilds SET Prefix = ? WHERE GuildID = ?",
AttributeError: module 'db.db' has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\events.py", line 61, in on_command_error
raise error
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'db.db' has no attribute 'execute'``` Am trying to change my prefix but it wont work
And like i have created a table on the sqlite browser table
ok ok
@placid skiffthen how do i send len of banlist
@bot.event
async def on_ready():
print("--------------------------")
print("[1] Nitrado Obelisk - Online")
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"Gameserver!"))
players_online.start()
status.start()
@tasks.loop(seconds=60)
async def status():
(...)
@tasks.loop(seconds=60)
async def players_online():
(...)
26.05 10:11:38 [Bot] File "/.local/lib/python3.9/site-packages/nextcord/client.py", line 417, in _run_event
26.05 10:11:38 [Bot] await coro(*args, **kwargs)
26.05 10:11:38 [Bot] File "/./Main Development (Nitrado)/Source (Nitrado)/main.py", line 25, in on_ready
26.05 10:11:38 [Bot] status.start()
26.05 10:11:38 [Bot] NameError: name 'status' is not defined
Can someone help with this? I'm unsure why my task loop will not start.
Would it be the inner part of the code, it's saying it's not defined
I'm unsure
change the activity in the Bot constructor π
How to make it so the bot can understand lowercase letters and uppercase letters?
players_online.start() works?
.lowercase
Yes, that works perfectly fine.
I tried the code, it was working earlier on, now it's not for the status
hm
What if user enters uppercase?
well don't put the tasks' starts in on_ready
nothing that you put in on_ready should be in on_ready
I want it to understand only letters and not care about the size
elif message.channel.type == discord.ChannelType.private and message.content == "None":
await channel.send("Nickname wasn't changed.")```
Ahhh, I didn't know that.
Do you mind showing me where else to put it? Or how.
Been doing it since day one lol
can you show the code how you open the database?
bot = commands.Bot(..., activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="Gameserver!"))
@bot.event
async def on_ready():
print("--------------------------")
print("[1] Nitrado Obelisk - Online")
@tasks.loop(seconds=60)
async def status():
(...)
@tasks.loop(seconds=60)
async def players_online():
(...)
players_online.start()
status.start()
bot.run(TOKEN)
You mean this?
async def on_ready(self):
print("Bot running with:")
print("Username: ", client.user.name)
print("User ID: ", client.user.id)
print('-----')```
though your tasks might need await bot.wait_until_ready()
Yeah, I was kinda doing a bad thing I didn't know of lol
Let me try to do this
How can I make my bot understand lower and upper case letters?
if message.content.startswith('N') and message.channel.type == discord.ChannelType.private:
await channel.send(f'Nickname set to **{message.content[1:]}**')
await member.edit(nick=message.content[1:])
elif message.channel.type == discord.ChannelType.private and message.content == "None":
await channel.send("Nickname wasn't changed.")```
if message.content.lower().startswith('n')
!d str.lower
str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
or upper tho
!d str.upper
str.upper()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to uppercase. Note that `s.upper().isupper()` might be `False` if `s` contains uncased characters or if the Unicode category of the resulting character(s) is not βLuβ (Letter, uppercase), but e.g. βLtβ (Letter, titlecase).
The uppercasing algorithm used is described in section 3.13 of the Unicode Standard.
I want my bot understand both
yeah that would work too
not only lowercase
!d str.capitalize
str.capitalize()```
Return a copy of the string with its first character capitalized and the rest lowercased.
Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
message.content.lower() then check it in lowercase
also, your bot will never enter this if statement
elif message.channel.type == discord.ChannelType.private and message.content == "None":
when the full message is in lowercase, then it would obviously understand
why not
yes
I want my bot to understand even If its NONE or none or NoNe
it's logical, if the person types None, the bot still enters the if statement before
and changes nick to "one"
if message.content.lower() == "none"
NONE, NOne, NoNe, these well all be none when you use lower() on them
^^^
it's all lowercase
huh?
then you can just check if its none
I don't understand
How do you kick someone from a voice channel?
!e ```py
test = ["NONE", "none", "NoNe"]
for x in test:
print(x.lower())
print(x.lower() == "none")
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
001 | none
002 | True
003 | none
004 | True
005 | none
006 | True
yep
yep
yep
So I can just type this users who type None will get their response message?
This is not what I meant
no cuz your logic is not flawless
make sure you understand the code
And noNe and nonE
@cloud dawn maybe?
and NoNe
1sec lmme look at my code
Just pass None when moving them
member.guild.voice_client.disconnect()
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have the [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to
use this...
That's the bot.
Changed in version 1.1: Can now pass None to kick a member from voice.
thanks
Sure give me one sec
can you give a string an attribute
a what
!e
e = "Hello"
e.randomattr = "Bello"
print(e, e.randomattr)
@heady sluice :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'str' object has no attribute 'randomattr'
nah
Are you meaning this? ```from os.path import isfile
from sqlite3 import connect
from apscheduler.triggers.cron import CronTrigger
DB_PATH = "./data/db/database.db"
BUILD_PATH = "./data/db/build.sql"
cxn = connect(DB_PATH, check_same_thread=False)
cur = cxn.cursor()
def with_commit(func):
def inner(*args, **kwargs):
func(*args, **kwargs)
commit()
return inner
@with_commit
def build():
if isfile(BUILD_PATH):
scriptexec(BUILD_PATH)
def commit():
cxn.commit()
def autosave(sched):
sched.add_job(commit, CronTrigger(second=0))
def close():
cxn.close()
def field(command, *values):
cur.execute(command, tuple(values))
if (fetch := cur.fetchone()) is not None:
return fetch[0]
def record(command, *values):
cur.execute(command, tuple(values))
return cur.fetchone()
def records(command, *values):
cur.execute(command, tuple(values))
return cur.fetchall()
def column(command, *values):
cur.execute(command, tuple(values))
return [item[0] for item in cur.fetchall()]
def execute(command, *values):
cur.execute(command, tuple(values))
def multiexec(command, valueset):
cur.executemany(command, valueset)
def scriptexec(path):
with open(path, "r", encoding="utf-8") as script:
cur.executescript(script.read())
cur.execute()
wait
yes, so you want cur.execute( ... ) not db.execute( ... )
im not sure, thats why im asking
because if they are importing it then it should work iirc
Yes db is imported
well try putting the stuff in db.py in a class and then call the class in the main file
Should i put that in #databases
I don't recommend copying code from git, especially code from 2020 https://github.com/Carberra/updated-discord.py-tutorial/blob/master/lib/db/db.py
oh well
if it works then it works
i wont bother touching it
Guys how can we use buttons in discord.py 1.7
Got told that in the dpy server- they said they're too lazy to code π
imagine wrong code from git
no buttons only available in 2.0
You can't without 3rd party libs
Like is ther rany module for it
Can you tell me a module for it
just use 2.0, it's better
Agreed
Cause me use replit and keeps changing to 1.7
Safer, too.
Not everyone.
Imagine getting hecked by a random 3rd party module
imagine having to use multiple modules for the same service
because you need to change the poetry dependencies
Hm?
How do you make so that all the buttons are disabled when one button is clicked and at the same time send an embed?
Loop through self.children and set .disabled of each to true
Can I have an example?
Guys, I am making discord bot tutorial, what do you think of this learning route? Should I add some other points into it or it is okay
well you could have a disable_all method in your class and just call that in each button
Nah, I don't have a class for interactions, I just do it in the command function
So you don't have a view subclass and you're just adding buttons to a view instance?
Oh heck
Looks pretty good
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
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.
that's a long command damn
lol
Bro, I can't rewrite with a subclass help me :cri:
It's ok you can still have a disabled function
So what do I do?
Make a function, call it in the button callbacks
I use this server_name = client.get_guild(int(server_id)) to get the server_name and print None
Imo subclassed looks much neater
returns none if not found
Still, I wrote it already :cri:
π
:cri:
disabled function? what parameteres should it take?
Trying to wrap my brain around how to do this without class hmm
@upbeat gust ```py
for server_id in servers:
server_name = client.get_guild(int(server_id))
print(server_name)
take the view instance and interaction
Oh also, after disabling them you need to edit the original interaction message and set the view to your instance
get_guild will return a Guild object, not the name
That I know
get the .name attr
Phew, Ima rewrite
@upbeat gust I'm gonna rewrite but tell me this time how to setup this whole thing
Eh you don't have to rewrite
How can pls help me
Will you dm me the things I have to do
Nah, there's some problem with the inventory thing, I have to rewrite anyways
when I print the type of server_name return NoneType
that's what happens when it can't find a server
how do i add nightcore effect to my music bot
@upbeat gust help me this time ima add a subclass pwease help :verysedcat:
bit busy rn
:verysedcat:
and this server_name = client.get_guild(880403606619160646) print None and this id is a server I am sure the bot is in
poetry add ......
replace ... With the lib you want
Use git+ followed by the github link if you need that
how do i make a nightcore music bot
You might need guild intents
That's a very broad question
I receive the message but can't detect the message edit. what am i doing wrong
class CogName(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.author.id == userid and message.channel.id == channelid:
print("ping")
try:
wait_edit = await self.bot.wait_for('on_raw_message_edit', check= lambda p: p.message_id == message.id, timeout=10)
print("Message edited")
except asyncio.TimeoutError:
print("Timed out!")
I print the intents and is 32767 and I think this is all intents
try print(list(intents))
awwwwww
How are userid and channelid defined
wait_for events doesn't have the on_ part
And yeah you don't need on_raw_message_edit use simple on_message_edit
all the intents are true
This too (and probably this is the issue)
π thanks guys
how to get online members?
ok then tell me how to make a command to record in voice channels
Is this even allowed by tos
there are verified bots doing this
It's undocumented
probably yes if the users know
Idk if the bots can receive incoming audios tho
mee6 can record bro
how to get online members?
Presence intent enabled and this code
online_members = [m for m in guild.members if m.status != discord.Status.offline]```
Hmm do i need to update all packages?
Like aiohttp and many more
ok im trying to run checks from a list. for example
permcheck = [administrator, view_audit_log]
how can i run for each item in the list and get them in a second variable
ummm. idk lol.
im trying to run a check on a list of permissions using inter.me.guild_permissions i need to add the item in i to the end so it would be inter.me.guild_permissions.administrator
https://github.com/MenuDocs/Discord.PY-1.x.x-Tutorials/tree/Episode-19 For this one is the json module suppose to be in cogs folder or outside?
The code for the discord.py tutorials on the MenuDocs youtube channel. - GitHub - MenuDocs/Discord.PY-1.x.x-Tutorials at Episode-19
your config and utils folder don't have much to do with cogs, you can move those to the root of your project
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\config.py", line 9, in <module>
import utils.json_loader
ModuleNotFoundError: No module named 'utils.json_loader'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\launcher.py", line 40, in <module>
bot.load_extension(f"cogs.{file[:-3]}")
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.config' raised an error: ModuleNotFoundError: No module named 'utils.json_loader'```
So?
@client.command(name='eval', pass_context=True)
@commands.is_owner()
async def eval_(ctx, *, command):
res = eval(command)
if inspect.isawaitable(res):
await ctx.send(await res)
else:
await ctx.send(res)β
How it is supposed to work
Its a command to eval a script
?
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code thatβs executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
So instead of eval(command) do exec(command)?
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\config.py", line 9, in <module>
import utils.json_loader
ModuleNotFoundError: No module named 'utils.json_loader'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\launcher.py", line 40, in <module>
bot.load_extension(f"cogs.{file[:-3]}")
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.config' raised an error: ModuleNotFoundError: No module named 'utils.json_loader'```
So?
@bot.command()
async def invite(ctx):
v= Buttons()
v.add_item(discord.ui.Button(label="Invite",style=discord.ButtonStyle.link,url="https://github.com/lykn"))
await ctx.send("Invite link",view=v)
Pls anyone help me fix
I am getting an error in it
what's the error?
You haven't import the Button class
Hmm
Hey, I have an ongoing subscription email that I would like to be posted on my Discord server (i.e whenever the sender sends me an email, Python sends a webhook to a specific channel). How do I extract the title, content, and overall email?
and btw view attribute in send method takes a View object, not a Button
Oh from duscord import butto
Idk is it? I use exec in my bot and R. Danny also uses exec
This is not related to discord bot
it depends on the package that you are using
oh im just dumb then
yeah could you tell me what packages I can use and how to use them?
I've never extracted content from emails before
Well the function itself doesn't block, what blocks is the code u exec
Neither i did
This channel is for discord bot, ask in some general help channel
yes i meant that
please claim a help channel -> #βο½how-to-get-help use smtplib for that purpose though
Then, yes. I mean, I once ran an eval- time.sleep(100) and uhhh, had to restart the bot
but further questions should not go here
you could just wait-
The console was spitting out logging errors
imma try that with the python bot now
Lmao it won't work
pffttt
!e import time; time.sleep(100);print(1)
@maiden fable :warning: Your eval job timed out or ran out of memory.
[No output]
See
weird
from root, to get to the json_loader file, you'll have to do
Path(__file__) / "cogs" / "utils" / "json_loader.py"
maybe that clears things up
It just cancels the further execution
If the sleep period is too long
welp
Guys can anyone help me how can we make url button in discord.py
!d discord.ButtonStyle.link
Represents a link button.
Set the button style to that
code
@bot.command()
async def invite(ctx):
v= Buttons()
v.add_item(discord.ui.Button(label="Invite",style=discord.ButtonStyle.link,url="https://github.com/lykn"))
await ctx.send("Invite link",view=v)
I got this from a git
What's Buttons()
I got in a git
Did u mean ui.View()?
What line to put that on
?
https://paste.pythondiscord.com/zabiqijobu this is -utils - json_loader.py
This is config.py file https://paste.pythondiscord.com/agogolasiq
okay....this thing has been pricking me lately that....why does discord.py's event on_member_remove still returns a Member object even though the user isnt part of the guild anymore
Why you will need a user? generally you use this to get what member exit from what guild
nvm didnt understand my point
It returns the member as they were right before they left
Also itβs more of a question to ask why does discordβs API do that rather than discord.py
hm weird
Guys can anyone give me example of a url button comamnd
Me not able to find a good tutorial
More of a design choice than a logic choice because as mentioned already thereβs no point in getting a user object
hm yeah yeah
Pls help
Yes. Sorry had got off the bus and had a final.
Anyone have any simple database code that is reccomended for a bot?
Wut
Yeah like you could get member's roles right before they left for roles keeping feature
you have to understand relative paths
I do and i did put them on the line that it needs to be put in but it still doesnt work
K
not true, the API gives you a user object
in that event, they first use guild.get_member(id) to get you the member object, and then remove the member from their cache
discord/state.py lines 1006 to 1018
user = self.store_user(data['user'])
raw = RawMemberRemoveEvent(data, user)
guild = self._get_guild(raw.guild_id)
if guild is not None:
if guild._member_count is not None:
guild._member_count -= 1
member = guild.get_member(user.id)
if member is not None:
raw.user = member
guild._remove_member(member)
self.dispatch('member_remove', member)```
hence, allowing you to get that user's Member object.
still doesnt make sense, I literally asked, why?
since the User isn't a Member anymore
library users would like checking what was the Member state before they left, like their roles, permissions, etc. which is really used by bots widely, so that should make sense
hm
from discord.ext import commands
TOKEN = 'Token'
bot = commands.Bot(command_prefix="!")
@bot.command()
async def vkc(ctx):
allowed_mentions = discord.AllowedMentions(everyone = True)
await ctx.send("@everyone Det er jump i C! Join VK C nu!", allowed_mentions=allowed_mentions)
bot.run(TOKEN)```
how do i get so that the bot reacts to the message its sends?
store the send method in a variable as it returns a Message object, then use the add_reaction method on the Message object to add reactions
my bad-
assign a variable to that message, and use variable.add_reaction
msg = await ctx.send("....")
await msg.add_reaction(emoji here)
Thank you
yeah thats the reason that question about the dpy event came into my mind lol
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
or you can use the escaped name of the emoji
<:name:id> for static emojis
<a:name:id> for animated emojis
but when i do like this
await msg.add_reaction(": grining π
it's just shows ...
and in vsc
its says unknown emoji
how do i constantly check if a member's status
like
if they're online, offline, dnd or idle
!d discord.ext.tasks.loop use a task
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with
optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
tysm
!d discord.Member.status
property status```
The memberβs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
welcome
Do anyone know how can we send a url button i saw the link example from the guy but i have no url button
Pls anyone anyone send me a example here
view = discord.ui.View()
view.add_item(discord.ui.Button(style=discord.ButtonStyle.url, label="", url=""))
Sheesh
how can i remove the (' at the beginning. also how do i check if the end is true and remove the ', True) if true and ', False) if false
('external_stickers', True)
('send_messages_in_threads', True)
('start_embedded_activities', True)
('moderate_members', True)
Simple xd remove itβ¦β¦
well heres the code lol
@commands.slash_command(name='permissions')
async def permissions(self, inter):
permissions_list = inter.me.guild_permissions
permslist = []
perm = ['administrator','view_audit_log','attach_files']
for perm in permissions_list:
if perm in inter.me.guild_permissions:
print(perm)```
That is a tuple, so you want to get the first element of the tuple? You just simply need to index it, tuple[0]. In your case, it's perm[0].
can you do a simple example and use the !e to show how it works?
!e
a_tuple = ('external_stickers', True)
print(a_tuple[0]) # The first element of the tuple
print(a_tuple[1]) # The second element of the tuple
@visual island :white_check_mark: Your eval job has completed with return code 0.
001 | external_stickers
002 | True
Anytime!
Tuples are like lists but they can't be changed, this makes them a bit more efficient!
can i add to an embed so if i have
HEHEHEHE
in the embed
can i add
UwU
to it so its
HEHEHEHE
UWU```
Oh and im using disnake
Do you want to edit the embed?
I don't really understand what you mean, but probably you want to edit the existing embed (assume it has the title "HEHEHEHE") and add "UwU" to it. Firstly get that embed (maybe using Message.embeds[0]), then, access the title attribute, and add "UwU" to it, finally, edit the message.
It would be something like this:
embed = disnake.Embed(title="HEHEHEHE")
message = await channel.send(embed=embed)
new_embed = message.embeds[0] # Message.embeds returns a list, so just index the first element
new_embed.title += "UwU"
await message.edit(embed=new_embed)
i was wanting to ammend the embed lol
hmm that looks about what i was looking for lol. i will work off that. thank you
note: you didn't edit
@client.command(name="command")
async def _command(ctx):
await ctx.send(f"y or n")
# This will make sure that the response will only be registered if the following
# conditions are met:
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower() in ["y", "n"]
msg = await client.wait_for("message", check=check)
if msg.content.lower() == "y":
await ctx.send("You said yes!")
else:
await ctx.send("You said no!")```
can i know how this work
def check(msg) i am having problem with this line
Pretend that didn't happen 
Have you seen functions defined inside of functions before or is it the code itself that confuses you?
i can understand how check is geting (msg)
only that
left is easy
Why is it indented
my friend gave me
he was learning about this, and this confused me
Oh
You pass the check to discord.py inside of wait_for(), it will then be called for every message and when it returns True await client.wait_for(...) will return with the message.
hmm
The function you passed to the wait_for is called everytime an event is dispatched (received) by your bot, then discord.py calls that function and passed Message to that function (This is determined from what the event is).
thanks
msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["y", "n"] becomes True or False, because it is a condition
Guys how can we edit a message multiple times in discord.py
number = int(button.label) if button.label else 0```
What does this mean
if button.labe else 0
number = int(button.label) if button.label else 0
this is equivalent to
if button.label:
number = int(button.label)
else:
number = 0
number = button.label or 0
``` π hmm 0 will result false I presume.
await ctx.send("Lets Start this giveaway, answer the questions I ask and we can proceed.")
questionList =[
["What channel should it be in?", "Mention the channel"],
["How long should this giveaway last?", "d|h|m|s"],
["What are you giving away?", "E.G. Pizza"]
]
answers = {}
for i, question in enumerate(questionList):
answer = await GetMessage(self.client, ctx, question[0], question[1])
if not answer:
await ctx.send("You failed to answer, please answer quicker next time!")
return
answers[1] = answer
embed = discord.Embed(name="Giveaway Content")
for key, value in answers.time():
embed.add_field(name=f"Question: `{questionList[key][0]}`", value=f"Answer: `{value}`", inline=False)
m = await ctx.send("Are all these valid?", embed=embed)
await m.add_reaction("β
")
await m.add_reaction("β") ``` get message is not defin ed
need help with designing a command that combines 2 commands
uh?
lets say i have an ocr command that reads text from an image, and a translate command that translates text. i want to make ocrtranslate command which does both at once
ashley any ideas for my code
ideas as in?
like how to fix.
lemme see
btw im using another file aswell ```import discord
import asyncio
async def GetMessage(
client, ctx, contentOne="Default Message", contentTwo="\uFeFF", timeout=100
):
embed = discord.Embed(
title=f"{contentOne}",
description=f"{contentTwo}",
)
sent = await ctx.send(embed=embed)
try:
msg = await client.wait_for(
"message",
timeout=timeout,
check=lambda message: message.author == ctx.author
and message.channel == ctx.channel,
)
if msg:
return msg.content
except asyncio.TimeoutError:
return False
@bot.command()
async def meow(ctx):
ew = bot.get_cog("GenCommands")
for commands in ew.commands:
print(commands)``` whats wrong, no response, the cog name is right and loaded
so how do i design it so that theres little code duplication
The code I sent was verified by danny himself
as if that means anything
try using:
im confused sorry
!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.
cry about it
wut
Who's danny?
i dont need to cry as im not a dpy user lmao
creator of discord.py
rapptz
who's rapptz
Danny
who's danny
btw im using another file aswell ```py
import discord
import asyncio
async def GetMessage(
client, ctx, contentOne="Default Message", contentTwo="\uFeFF", timeout=100
):
embed = discord.Embed(
title=f"{contentOne}",
description=f"{contentTwo}",
)
sent = await ctx.send(embed=embed)
try:
msg = await client.wait_for(
"message",
timeout=timeout,
check=lambda message: message.author == ctx.author
and message.channel == ctx.channel,
)
if msg:
return msg.content
except asyncio.TimeoutError:
return False
^
ok
Does that work ?
try it and see
I use hikari
whos danny
my mom
dunno i asked first.
Iβm on mobile so I canβt see if it works
π³
Owner of discord.pyβ¦.
yeah indeed he owned this library hard..
only persons i know is eq and epicπ³

pewdiepie
yes
Maby danny
yes danny wrote all discord api wrappers
panda
Yes?
in all languages
panda is the creator of this world
nice project
is it on github?
I took a nap on the 7th day true story.
check her desc
i dont see the world project there
Bruh my repo's suck
no no
It's just to cover your own ass.
I used to things its
Massachusetts Institute of Technology
ew = bot.get_cog("GenCommands")
for y in ew.commands:
await ctx.send(y)
no response, the cog name is SURELY Valid i double checked and copied
Me Is Tired
lol
is there a premade embed paginator?
theres allot of exts ive seen
show traceback?
well because it gets kinda messyπ
beware theres allot of extensions with trash impl!
im looking for the simplest solution
2 buttons/reactions that scroll backward/forward
i just pushed a pull request to disnakes repo
ew = bot.get_cog("GenCommands")
for y in ew.commands:
await ctx.send(y)
no response, the cog name is SURELY Valid i double checked and copied
ok
hm, which library?
disnake
paginator?
hm
what are you asking
disnake is discord api wrapper
im looking for a simple embed paginator that has 2 buttons or reactions that make it able to scroll backward or forward
oh
i even improved one
which
the error is GetMessage is not defined
but idk if i need to import from the other file or whatever
_var is meant to show that a name is private.
var_ should be used if var name is already taken.
Reference: PEP8
ofc you have to import functions presence in other files...
so from utils import GetMessage?
2 lines changed, still better
yes?
ok
if thats your file name
lol that was a joke commit but they accepted it
well tbf im still correct so i dont mind
why was that command private and why did you moved the underscore, you shouldve removed itπ
because bot is already defined
i wonder why the function name is even named bot
π

