#discord-bots
1 messages · Page 828 of 1
what's even happening here
idk, I'm annoyed
Still?! Smh
yeah
@nimble plume u have to do something like
embed = disnake.Embed(...)
embed.add_field(name=..., value=...)
await channelslogs.send(embed=embed)
And yea, @slate swan drink some water and calm down
I will, need to, thanks
Cool
can a discord bot find out if a user is server booster? if yes, how?
!d discord.Guild.premium_subscribers
property premium_subscribers: List[discord.member.Member]```
A list of members who have “boosted” this guild.
Yea the bot
oh and can a discord bot access and show a users profile banner?
!d discord.Member.banner
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.banner "discord.User.banner")
o
If the guild instance is guild, then do guild.premium_subscribers
It's an attribute
Hey does anyone know how to do ctx with on_member_join
You don't
why isnt Member.banner working for me
@bot.command()
async def banner(ctx, member: discord.Member):
await ctx.send(member.banner)
or does it have a workaround such as discord.File
oh
Welp then my plan failed hard I am attempting to have an on member join check a database to see if the members been there before and if they have notify the owners
AttributeError: 'Member' object has no attribute 'banner'
Are you using dpy 2.0?
You can still do that
update to the master branch or use a fork
i used python3 -m pip install discord.py
pip install -U git+https://github.com/Rapptz/discord.py
What’s the point of the -U if it’s gonna pull from master anyway?
If they already have discord.py installed it won't update, -U flag is used for update if exists
now its giving AttributeError: 'NoneType' object has no attribute 'url'
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.banner "discord.User.banner")
ah alright
!d discord.User.banner
property banner: Optional[discord.asset.Asset]```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
read the note
thank you
AttributeError: 'NoneType' object has no attribute 'url'
@bot.command()
async def banner(ctx, member: discord.User):
user = await bot.fetch_user(member.id)
await ctx.send(user.banner.url)
Changed from member: discord.Member to member: discord.User because member is a child of User and User contains id but it still isnt catching up it's id
usage: ,banner @vdev
you user variable returns None
it should be getting the fetching user data from what i know
does the user have a banner
Banner is none
Aka, no custom banner
oh ye ye ye ^
oh, i thought its code error because it was throwing errors, shouldve tried it with avatar
thank you
hmmm
also hello @maiden fable
Wdym
press on my profile, and the blue area above my pfp
thats the banner correct?
Yeah
but when someone again reacts to the quote
it resends it again
how to fix that
Append the user to a list
howw
Make an if statement. If the user is inside the list then you ignore it
!d discord.Member
but
You know how to append to a list, right?
i.. am new to python
list.append(values:type)?
Kinda
oh
isn't bot.listen() old?
🚪 🏃♂️
but.. it works
No
oh k lmao
Here im trying to get user avatar
@bot.command()
async def avatar(ctx, member: discord.Member):
user = await bot.fetch_user(member.id)
await ctx.send(user.avatar.url)
And I'm getting this.
Usage: ,avatar @vdev
So it’s list_name.append(values)
Not really
So yes exactly what u said
user.avatar can be None if there's no Pfp
This may also error, the user can have no avatar resulting in None
list.append(values:type) isn't the same as list.append(values)
i want that count
its impossible to have no avatar since discord itself asigns the user avatar by creating account, but i will try
What is this for
default avatar is None
Yeah, that default avatar is no avatar for dpy
im making custom starboard
!d discord.Member.default_avatar
property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.default_avatar "discord.User.default_avatar")
Hi
I see
This is for one provided by disx
Oh thank you all, didn't know default_avatar existed
can i fetch it in anyway
do you know what class properties are
i....
!d disnake.User.display_avatar if you use Disnake something smart like this exists too.
property display_avatar: disnake.asset.Asset```
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
oh no
am new ;-;
not another one that doesn't know python and using dpy
!d discord.Member.display_avatar also exists (:
property display_avatar: discord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
anyways properties are getters and setters
Are you using dpy 2.0
python's way is different from other langs like c# where you do
public string Name { get; set; }
No
No, download from github
pip install git+https://github.com/Rapptz/discord.py
On pypi it's 1.7.3
.does pypi stand for python package installer
PYthon
Package
Index
btw does anyone know how to make a bot send msges on server privately (like when it says only u can view this msg)
ok
interactions?
💀

!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
do u know the code for it?
(:
thx
does anyone know how to merge the commits of the original repo with a fork?
make a PR on the original repo
Uhhh?
Go to pull requests and click on the blue link
its for jarvide, i have a pull open but its so many commits ahead
Jarvide is still alive?
yeah?
Host on a vos
Host it
or at least last for the day
VPS*
without paying
Use a host
Run your computer 24/7
Run the bot in my head get a vps
electricity bill
lol
still paying for the electricity
lol
on my repo or the original one?
@dense swallow
I'm assuming they're not paying their electricity bill
- Read pins.
- Buy a good host.
- Use a free host.
- https://railway.app
🗿
i said for free
finally kayle didn't suggest replit
yeah.
"buy" lol
option 3/4
how do you know that
They do?
- bad IDE
- bad font
- only two themes
- lags like hell
replit is so bad 💀
Free or paid?
Vultr
it's good.
Sneakyhub, Epikhost and railway app works for me
people just misuse it's purpose
vultr is paid
lol
You won’t really get a good and reliable host for free
Aws/google cloud.
sad
i was thinking to make a bot that spams watch add button on bdfd
BDFD?
Whats BDFD
oh
samething
Isn't that an app on mobile
I've used it before when I was a skid, BDscript is bad
ik
time to watch ads
oof
jk
i will not
if you can get GitHub students pack, replit hacker plan is an option too
i alr get 2x 20 second unskippable ads on youtube
im not gonna watch more
how can i pass a ctx parameter in the command? such as setting default response?
such as
async def avatar(ctx, member: discord.Member = ctx.message.author.id):
can someone help me link two python files for discord?
import .filename
yes
ye
with a period
yes
?????
my bad
whats the file extension?
- bad linter for gods sake
someone help me with this
- they change everything every 2 seconds
no
- repl is having trouble loading files, refresh o fix it
use the or keyword
says its an invalid syntax
member: discord.Member=None
ctx: commands.Context
member = member or ctx.author
- cant have secrets in mobiile view
ty
whats the file extension?
u need the full file name
whole replit marketing based on live share lmfao
NameError: name 'member' is not defined
async def avatar(ctx: commands.Context,member: discord.Member=None, x = member or ctx.author):
in the command
x= in the command
dont u create var x?
ohhh, that didnt come to the idea, thanks
no module named cmnds.py found
its a temp var
ahh
what is your file structure
So my bot kept telling me that I was exceeding the 1024 char cap on a embed field value which I don't think I was but okay I guess. To remedy this I decided to split the responses up into separate pages and paginate them but It's still giving me the same errorpy HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embed.fields.1.value: Must be 1024 or fewer in length. In embed.fields.2.value: Must be 1024 or fewer in length.so I'm thinking something is going wrong somewhere in my logicpy @commands.command(description = "Get this bots PoC's.", usage = "poc", hidden = False) async def poc(self, ctx): pages=[] first = discord.Embed(title = f"Point of Contact(s) for {self.bot.user.name}", colour = self.bot.primary_colour) pages.append(first) for guild in self.bot.guilds: embed = discord.Embed(title = f"Point of Contact(s) for {guild.name}", colour = self.bot.primary_colour) admins=[] mods=[] pocs=[] for member in guild.members: if member is guild.owner: embed.add_field(name = "Owner", value = guild.owner) elif member.guild_permissions.administrator: admins.append("{member.name}") elif member.guild_permissions.manage_messages or member.guild_permissions.manage_guild: mods.append("{member.name}") else: if member.id == self.bot.config.admins: #member_mention = "<@{member.id}>" pocs.append(str(member)) embed.add_field(name = "Admins", value = ', '.join(admins)) embed.add_field(name = "Mods", value = ', '.join(mods)) embed.add_field(name = "Other PoC(s)", value = ', '.join(pocs)) paginator = Paginator(length=1, entries=pages, use_defaults=True, embed=True, timeout=120) await paginator.start(ctx)
The error is quite easy to understand
It’s something to do with the values of your fields
maybe print out the admins and mods variables?
it would be, if the list of admins and mods were long, but the guild with the most mods has 5 mods (so doubtful that that's hitting 1024) and the most admins on any of the servers is 2 (so three's no way that should be hitting 1024.
okay I'll try printing them but i'm thinking there's a logic issue
can I make this a deco?
async def check_if_can_ping(ctx, member : disnake.Member):
async with bot.db.execute("SELECT obj_id from mod_ping WHERE type = ?", ('Role',)) as cursor:
list_of_roles = await cursor.fetchall()
the_roles = [role[0] for role in list_of_roles]
list_of_author_roles = [role.id for role in member.roles]
common_role = (set(list_of_author_roles) & set(the_roles))
if common_role:
return False
else:
return True
or I could have been a total idiot and been adding the updated cog to the wrong directory and reloading the one in the correct directory
Decorator?
not sure if all that will be able to be used in a decorator
And decorators take in a function as a parameter and modify it
Maybe it could work if you did like
def random_name(func):
def wrapper():
func(*args, **kwargs)
return wrapper
I’m not the best with creating decorators and doing special stuff In them. Prolly should learn more about decorators though
Yups
hunter is prolly better than me at this 🗿
with add_check?
def cancel_long_invoke(timeout: int = 10, in_a_cog: bool = True):
"""This is what tells Python that it is a decorator which has to be called.
Remove this and u don't need to call the deco and the name becomes `deco`"""
def deco(func: Callable[..., Any]):
"""This is what Python does as func = deco(func)"""
@wraps(func)
async def wrapper(*args, **kwargs):
"""This is what is returned when the deco is used. Sort of, this is the command or u can say, the function"""
if isinstance(args[0], Context) and not in_a_cog:
ctx: Context[Bot] = args[0]
elif in_a_cog:
ctx: Context[Bot] = args[1]
task = ctx.bot.loop.create_task( # type: ignore
wait_for(
fut=func(*args, **kwargs),
timeout=timeout
)
)
try:
return await task
except TimeoutError:
task.cancel()
return await ctx.send(f"Hey there! Sorry, but the command timed out after {timeout} seconds, {ctx.author}") # type: ignore
return wrapper
return deco
I added some help docstrings in the long invoke thing, I guess this can help
I also never understood decos tbh. Gotta learn more about them haha
I'm trying to make my bot skip over bots if it finds them in the members list, this is how I dentify a bot right? if so should I be passing, returning or continueing in order to make to skip over bots whilst will executing the rest of the code```py
for member in guild.members:
if member.bot == True:
return
if member is guild.owner:```
what abot add_check?
how can i make a 'copy' button which copies some text into the clipboard of the button presser?
!d discord.ext.commands.check has a cleaner interface
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
i did fetch upstream... showing that branch has conflicts that must be resolved
that means that there are issues with the branch you are trying to merge with the master branch
Or have you merged it already?
there could be competing lines Changes which can cause merge conflicts. Only those can be solved on GitHub
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
U do know that this isn't the correct channel, right
I told him to go to #tools-and-devops earlier
Oh wait, nvm
Rip
how do i add a task for my bot? like checking a the time constantly
Like a normal task
yes
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
nice
You can make cron tasks with apscheduler
U can also use the time kwarg BTW
Ignoring exception in view <SnoozeButtonView timeout=60 children=1> for item <SnoozeButton style=<ButtonStyle.secondary: 2> url=None disabled=False label='Snooze Reminder' emoji=None row=None>:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/discord/ui/view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "/usr/local/lib/python3.9/site-packages/discord/interactions.py", line 423, in defer
await adapter.create_interaction_response(
File "/usr/local/lib/python3.9/site-packages/discord/webhook/async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```Does anyone know what this error means? How can I know which line of code is raising it?
Are you responding to the interaction within 3 seconds?
Possibly, yes
Ah wait
No
I wait for the "..." ellipses to go
Then select from the Select (dropdown)
guys
if i wanna start learning python
where do i start
what is the minimum requirement?
🤔 this looks like it's from a Button though
hey i want to create a programm that lets u check other ppl's usernames what should i use
I press a button. That button then turns into a dropdown (editing the message's view kwarg), which results in the "..." and then this "interaction failed". I then select from the dropdown, and get that error
i see
should i use a dict or a library for that
But what I don't get is my callback function runs fine with no issues
And my @ui.select one
??
Are you using an InteractionResponse methods after 3 seconds of receiving an interaction?
async def callback(self, interaction: discord.Interaction) -> None:
"""Ensure the reminder author matches the user who clicked button and then display select view."""
if interaction.user.id != self.parent_view.reminder_author_id:
await interaction.response.send_message(":x: This is not your reminder to react to!", ephemeral=True)
return
snooze_select_view = SnoozeSelectView(
bot=self.parent_view.bot,
reminder_id=self.parent_view.reminder_id,
reminder_author_id=self.parent_view.reminder_author_id
)
m = await interaction.message.edit(view=snooze_select_view)```here's how I'm changing the view if that matters
why no1 helps D:
It's because you changed the codebase completely by not syncing your repo with the main ones
I'm using InteractionResponse methods, but no clue if it's after 3 seconds of receiving the interaction (they do run without error though)
try interaction.message.edit -> interaction.response.edit_message
It couldnt find the client which invoked the command
I've got that in a try/except so I know it's not causing the error
Thats a different issue
!d discord.Interaction.message
I'd still recommend trying it since it makes sense logically (Interaction Failed because you aren't responding to the interaction)
Right, I'll try
It's not a command though
could you elaborate please?
Then it couldnt find the client which pressed the button
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
Or User
Interesting. I've now got a different error (which ik how to fix)
As you please
@bitter depot the most common way to fix that error would be to first to interaction.defer and then using followup to send/edit or anything else
you wouldn't be able to edit the original message with followup
Well yea facts... But that's what everyone uses to prevent that error
It seems to be working after Zeffo's suggested change
Ah cool
Which is really annoying because I literally put a try/except around it
Haha
Thanks Zeffo, it's working perfectly 👍
Ignoring exception in command channel:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\testing\modules\config.py", line 63, in _channel
await self.channel(ctx=ctx, channel=channel, player=player)
File "c:\Users\PC\Desktop\testing\modules\config.py", line 55, in channel
raise commands.MissingRequiredArgument(param=channel)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\errors.py", line 171, in __init__
super().__init__(f'{param.name} is a required argument that is missing.')
AttributeError: 'NoneType' object has no attribute 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'
Code
read. the. error.
Bro?
All we can tell from the error is that param = None
Facts
and now they fade out of existance
never to be seen again
.. ok
no im here
send your code so we can help you with your error
async def channel(self, ctx = None, interaction = None, channel = None, player = None):
ch = ctx or interaction
func = ch.reply if ctx else ch.response.send_message
if not player:
raise commands.MissingRequiredArgument(param=player)
if ch.guild.id == 566648561840685057:
if not channel:
raise commands.MissingRequiredArgument(param=channel)
guild = self._bot.get_guild(566648561840685057)
category = nextcord.utils.get(guild.categories, name="TRACKING")
await self.category.create_text_channel(name=f"{player} {ch.user.name}")
@commands.command(name="channel")
async def _channel(self, ctx, player: str = None, channel: nextcord.TextChannel = None):
await self.channel(ctx=ctx, channel=channel, player=player)
yes did sorry
remove the = None on ctx
also is this in a cog?
yes
ok
i was gonna ask because i saw hte self
yeah just remove the = None on the ctx arg and ur good
well thaats whats causing your error
someone said its cause param is None
and its true cause im passing param player if its None so its obv its gonna be None
someone know what type should it be
just dont pass title argument i think
users = await ctx.message.reactions[0].users().flatten()
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
pardon?
embed=discord.Embed(title="test", description="test")
embed.add_field(name="test", value="test", inline=True)
embed.add_field(name="tes", value="tset", inline=False)
await ctx.send(embed=embed)
the name is bold
if i dont add any name is error
yes because add_field requires name and value
you can do it without the title
ik but the problem is not the title
the problem is "name"
embed = discord.Embed(
description = "This is a description only!",
color = 0xffffff
)
yes
yes you need a name
or you can make a new line using \n
^^
embed.set_image(url = user.banner.url)
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url' what do i do
Fetch the user/member first. banner properties are only accessible through fetch_x methods.
_user = client.fetch_user(user)
embed.set_image(url = _user.banner.url)
``` ?
is there another way of adding buttons to a message other than subclassing discord.ui.View
Yea
Yes, you also gotta await it
view = ui.View(timeout)
btn = ui.Button(...)
view.add_item(btn)
await ctx.send("Okay", view=view)
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
In user_id: Value "Niclas" is not snowflake.
i dont even know what snowflake is
the Button or the Dropdown u want to add
oh yeah and my spelling may be wrong because i got a new mechanical keyboard lol
could yoou show me an example
It should be an id
the user ID
@shadow wraith
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
oh alr
wth is that name
Can I make colours appear on discord?
I have an idea for a discord bot but it needs to utilise colours
yes
wdym by 'appear' though
So like letters in a word are different colours
I want to make a command that makes a word go a certain colour
u can use the ansi colour codes
How do I use them?
And do they work on mobile
Uh not sure
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
code block failure 😭
\u001b[0;31wat
cool
ios does not have colors 😞
!category @someone
How do I get the member's category?
For example there is a category called HANGOUT
and in the category there is a voice called Voice Ch #1
and someone is in there, so I did the command and I want to get his category name which is HANGOUT...
what does the ping have to do with any of that?
?
so you basically just want the bot to reply the category which a mentioned member (who's in a voicechannel) is in?
If someone is in a voice channel and I am pinging him so it i'll show the name of the voice channel the the member found in. (i did it)
now i want to get also the category name...
ok, show me your current code attempt
@client.command()
async def invc(ctx, catevc: discord.VoiceChannel, *, member: discord.Member=None):
if member is None:
return await ctx.reply("**:x: You have to mention a member!**")
if member.voice is None:
return await ctx.reply("**:x: The user has not connected to VoiceChannel!**")
category = catevc.category
vc = member.voice.channel.name
await ctx.send(f"User is in: `({category}) - {vc}`.")
It is not working..
@potent spear How can I fix it?
do you realize what this does *,?
alright, let's think about what you're doing here, alr?
discord.ext.commands.errors.ChannelNotFound: Channel "@shut axle" not found.
it's literally the second parameter in your function, after ctx
catevc: discord.VoiceChannel?
yeah, what's that doing there?
If I remove it, what can I do instead?
you must include catevc: discord.VoiceChannel
if you want to invoke it like !invc #discord-bots
but it seems you want ping user, not channel
I want to ping the member like that: !invc @member
to get his category name...
I already did it for voice name.
ctx, member: discord.Member
category = member.voice.channel.category
if i remember it right
yup, those 2 lines are all you need
category = member.voice.channel.category**.name**
?
Yeah sure
Thanks for pinging that poor person
Hi,new to python bots
pay close attention tho, some guilds might not have a category for some vcs
lol
Any idea how to make one?
xd
learn python first
then move on to
#discord-bots message
how do i access the bot user inside of a cog
self.bot
self.bot.user?
sure
srry bruh i have to use discord.py for over 2 years
how can i do a private message into a channel (like the print)
empheral=True
how do I make my bot pirnts its server ID when a user uses a specific command
e.g.
!test
bot: server {ID}
only works with interactions
am. check guild functions ig
ah okay
bruh
yes, thanks
ever written a command?
in docs it's a int
i have to pass i string and make it a int?
a typehint automatically converts it to an int
will you now start reading what I typed? orrrrr
async, def unban(self, inter, userID: int)
people sure have some weird ways to overcomplicate things
they do, but I like how he's trying
if you use "" instead of '' you wont need to use \'
^ best to stay true to the "/' you're using
you've got inconsistent usage of double and single
and ' doesn't look good with a sentence either
most of the langauges use it only for a character ( single character)
most code formatters change to " anyway
async def add(ctx, *, question):
embed = discord.Embed(title = "test", description = f"{question}")
await ctx.send(embed = embed)
how to send it in specific channel using channel id
how can I check if a user has more than a few days using discord? (using created_at)
Yep , atleast I'm sure about Julia and rs
you would use datetime.timedelta
thank you
use
stinky_text_channel = ctx.guild.get_channel(the stinky id)
await stinky_text_channel.send("shit")```
you can also use .created_at.strftime("")
oh true
alright
quite stinky ngl
it has to
I removed it
bot.get_channel(channelid)
await channel.send(embed=embed)
I just removed when u said
It was done by mistakely while edititng the code
Its my fault i didnt read what i send
I apologize for that
Hey guys, I'm trying to code an unban-command, but it doesn't work. I always get the same error. Maybe you know what I have to do.
Image doesn't load, but I'm sure it comes from Lucas?
Hm
!d discord.Guild.unban utilise this
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
member: discord.Member
See the loop inside it lmao
discord.py enforcing typehints:
and caeden is that you?
How do you unban a member
don't unban like that pls
use this instead
#discord-bots message
it indeed is
hello guys, how to get emoji?
im not paying attention 😢
people copy and pasting code
wdym
!d discord.Client.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
honestly, just unban hem yourself all you really need is a ban command
aa
whats the next /
i send my custom emoji to another server
thanks, now its working fine. Is there a way to unban the user based on the username?
when would this be useful?
I just realised that, but thanks man
anybody?
i have this small command but it send None on another server
@client.command()
async def emoji(ctx):
await ctx.send(":logoa:")
um u want to send ur custom private server emoji to other servers?
is the bot in both the servers
the bot has an emoji server where there are emojis. I want to send it to another server from there.
with select menus etc
hmm so basically is the bot in both the servers
lets name the emoji server as server1 and the final server as server2
so is the bot in server1 and server 2?
Use the escaped form of the emoji , you can get it using \emoji
for example for 
It's !yert
lol
yeah i have this but the bot send "None"
@client.command()
async def sendemoji(ctx):
emoji = client.get_emoji(":logo:")
await ctx.send(f'{emoji}')
the id in here but dc remove
thats definately not what i asked to do
you either do py emoji = client.get_emoji(emoji id here) or get the escaped name and py emoji = 'escaped name'
just send them like this
name:id
if they're custom and not animated ofc
<:name:id> and add a before first : if its an animated one.
ty its works
you never added the check in the wait_for
but that's not the issue tho
where do i add it
in the wait_for, it's in the docs
it isn't, but it will be very soon
do you even run the bot?
are you sure you're running the correct code/file too?
check it, dont be pretty sure.
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.
don't leak the token
yes
import discord
from discord.ext import commands
import random
import asyncio
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "-", intents = intents)
@client.event
async def on_ready():
print("Bot is ready")
print("-------------------------------------")
@client.command(aliases=['decideevent', 'eventoss'])
async def decidevent(ctx):
def check(m: discord.Message) -> bool:
if m.user == client.user:
return False
list=['event1', 'event2', 'event3', 'event4', 'event5', 'event6']
await ctx.send("First event:")
list[0]=await client.wait_for("message", timeout = 20)
list[0]=list[0].content
await ctx.send("Second event:")
list[1]=await client.wait_for("message", timeout = 20)
list[1]=list[1].content
await ctx.send("Third event:")
list[2]=await client.wait_for("message", timeout = 20)
list[2]=list[2].content
await ctx.send("Fourth event:")
list[3]=await client.wait_for("message", timeout = 20)
list[3]=list[3].content
await ctx.send("Fifth event:")
list[4]=await client.wait_for("message", timeout = 20)
list[4]=list[4].content
await ctx.send("Sixth event:")
list[5]=await client.wait_for("message", timeout = 20)
list[5]=list[5].content
reply=await ctx.send(":loading: Reestablishing the Caliphate")
await asyncio.sleep(1)
await reply.edit(content= ":loading: Taking the boats on a walk")
await asyncio.sleep(1)
await reply.edit(content= ":loading: Preparing with homies for Ghazwa E Hind")
await asyncio.sleep(1)
await reply.edit(content="The events have been decided by the council")
await ctx.send(random.choice(list))
client.run('token')```
did u assign token
your client run is inside your function
i did
take it out
wait
oh yes
also, fix your check, that'll be your next upcoming problem
lol
and how can i use it in menus?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.3.emoji.name: Invalid emoji
wdym by menus?
show code
hey all i am trying to make a simple discord bot with some basic commands could somebody help me learn some stuff like the basics how to make a bot ? if yes please dm me or respond to this message
"Select Menu"
use get_emoji method for that
if you're wondering what the id of the emoji is, those numbers in the escaped name is the id
move the emoji variable inside the function.
.
it isnt cached if its outside
true true
reading the docs, and asking questions would help
and its recommended to know a basic knowledge of python and OOP
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
e
but the problem is same
show new code
emoji=emoji in select option
hey first of all many friends told me to make projects. also, i don't understand what i am reading so i can't do smthing. Finally, none is helping me starting coding things
oh, do you have any experience with python?
thank you!!!!!!
no i don't
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
these are some helpful resources which will guide you!
if you face any issue, you may use the channels (depending upon kind of problem) of this server to help you.
i don't understand anything while i was reading the docs
its because you wont get many terms about programming without learning about the language first
reading the docs of basic python man
does it explain what everything does ?
there's no limit to "everything", but yes it explains python basics
and you can try your code at the same time.
yeah how do i try my code mate
you can write code too
from the terminal youll have to download a python interpreter and this isnt rreally on topic with this channel so you can ask more questions in #python-discussion
i have already downloaded iit
then you can run the code in the python idle
yes mate but idk what i can write
write a password generator or whatever you want
how and what is a password generator
modals need a custom id? or is that like a persistent modal?
btw can u help me personally in dms and stuff
with the random module and its just gets 10 or more random chars
ah ic havent worked with them yet and i dont think i will lolll
i haven't readed all these but can u tell me in dms personally and tell me what to do
Since it's new, you might be better off asking in the support server of the fork you're using since most of us have no experience with it
nah i dont help in dms or do tutors @quick gust does tho ask him to tutor you he knows more than me
i don't :(
someone from here asked me to help them with a self bot in dms lmao
lmfao not a "self bot" its againt discord terms of service
yes
i don't help with tos breaking stuff
yes mate i just want to start learning how to make a discord bot and stuff
I give you 5$ to help me in dms
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
tell me how to do the basics
which link
I'm bad at explaining, it's best u read that thread
i only do privs tutors for 100$😩
nvm got it
100$ for okimii tutoring
What a scam
When I met him he didn’t even know how to do list comprehension
yes! his tutions are priceless!
Well
It's not like we can teach you from the ground all the basic stuff
If you already know python you can start with the docs
bro that was a long time ago bro🏃
for x in range(1, int(amount) + 1):
user = ''.join(random.choice(string.digits + string.ascii_lowercase) for _ in range(4))
r = requests.get(f'https://tiktok.com/@' + user)
if r.status_code == 200:
print(Fore.WHITE+"🚫"+Fore.RED + "Taken"+ Fore.RED+ f' {user}')
else:
print(Fore.WHITE + "✅" + Fore.YELLOW + "Available" + Fore.YELLOW + f' {user}')
f = send()
It’s only sending 1 instead of amount
now i do list comps all day😩
Worth it bc your good at coding do you accept btc?
bro i started reading the docs but i didn't understand shit
im jokinggggggggg lmao im not a good teacher😭
youll need to learn oop async and basic py
Well I have decent grasp so it might work 😭
Already gave you a link to understand the basics, we really can't help you from scratch, it's not what we do professionally
1$ + a PR adding new colors in discordheximals 
what is these
how many
object oriented programming asynchronous programming and basic python
object oriented programming, async programming, basic oython
slow
nvm I'm slow
slow
erm yes man but i still won't understaand shit i will just have readed them
no no keep your money 😭
LOL
hold up ill give you all the links from google
okk
ok
have fun reading
how much time do u think its gonna take
depends
passion, how fast you learn, how much you learn etc
how would ik if i learned all these
i cant really say for you but for me it was 10+ months
yes man but idk if i learned all these
Umm, This might sound stupid, but how to do cycle statuses, I forgot how to do it, I know it's
,status = cycle(["status1","status2"]
But how do you get it to change like that, and how do you specify the seconds, can anyone dm me a solution?
youll know when you do
for x in range(1, int(amount) + 1):
user = ''.join(random.choice(string.digits + string.ascii_lowercase) for _ in range(4))
r = requests.get(f'https://tiktok.com/@' + user)
if r.status_code == 200:
print(Fore.WHITE+"🚫"+Fore.RED + "Taken"+ Fore.RED+ f' {user}')
else:
print(Fore.WHITE + "✅" + Fore.YELLOW + "Available" + Fore.YELLOW + f' {user}')
f = send()
The amount is only 1 when it’s suppose to be 9
And it’s not sending request with send()
maybe try session.get?
lol i can just read smthing rn and say that i readed all of them
Session for what
This is not the appropriate channel
O yea mb I always use discord bots sorry
well .send is a coro and request isnt async and why are you making an int an int
It’s checking if website gives status 200
delete this now
thxx
its horrible in every way
someone have idea what add to code to set how much winners in giveaway?
never seen something that bad
Are you fucking serious
You found the hardest way to do it 😭
You will prolly get rate limited for using same program for different Botd?
It's just 6-7 line of code you know
And the bot.listen ....
Event tho that doesn't affect the code, but yes that does not need to be there
Yeah, i'll go bleach my eyes
Ye
Elaborate logging? Saving them somewhere?
- the discord api has dynamic ratelimits
- tasks are a thing
- starting a loop on ready isnt the best thing to do
- why not on ready? on ready gets triggered many times as it gets triggered on cache population and if a bot gets disconnected from the gateway it will for sure trigger it again
- youll always have to wait for the bot to get ready first or the gateway will disconnect you
- hes talking about in the kwargs in the Bot class

I’m proud of you Okimii you’ve progressed so far 
the run method on the bot instance creates an infinite loop, so you shouldnt run multiple bots
import random
import time
import crayons
from discord_webhook import *
import random, string, requests, time
from colorama import Fore
import concurrent.futures
import os
print("{}".format(crayons.green('Made by: alexlol#001')))
def send():
webhook = DiscordWebhook(url=webhookurl, content="https://tiktok.com/@" + user)
response = webhook.execute()
webhookurl = 'web'
amount = 9
for x in range(1, int(amount) + 1):
user = ''.join(random.choice(string.digits + string.ascii_lowercase) for _ in range(4))
r = requests.get(f'https://tiktok.com/@' + user)
if r.status_code == 200:
print(Fore.WHITE+"🚫"+Fore.RED + "Taken"+ Fore.RED+ f' {user}')
else:
print(Fore.WHITE + "✅" + Fore.YELLOW + "Available" + Fore.YELLOW + f' {user}')
f = send()
time.sleep(1.65) #DONT CHANGE THIS!!
print('done')
time.sleep(5)
Anyone help?
i mean i remember when i was a beginner and i wanted to be like you robin hunter krypton andy and much more smart people started in march almost gonna have a year in experience so thats cool❤️ but i couldnt have done it without my brother @minor totem he guided me to the right course which i appreciate so much :))
Use a json or a seperate file?
that doesn't work, and I mean, like, having the code I have ,status = cycle(["",""])
I’ve coded since September I’m still bad
well i have allot of passion in what i do and this is gonna be my future job doing back end so maybe i do know more than others but i dont focus on that :))
Lord Okimii will help
👁️👁️
I want to code when I’m older because coding has relation to maths I’m really good at maths + I like technology and coding in general it’s just learning it
For job ^
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
will it depends on what fields tbh some fields do use math allot anyways ot #career-advice
does anyone have a better solution for cycling statuses?
Ij ust need to know the time bit
like how often to cycle
That's what i forgot
you can use next for it
Yea I’m planning on maths field because I’m good at subject and it’s probably not a popular career path so high income
hey! i'm pretty new to coding, only know a little python. I'm interested in discord bots, and i'm wondering where to start. any ideas?
!d itertools.cycle and use next
itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
```py
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
```...
What are you planning
not that,
well be prepared on allot of headaches 🏃
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
just something simple like a bot sending a message when a certain thing is said. I don't know much rn
There's no other way making changeable status without variables who changed with time then.
@slate swan heyyyy sarrrrr
Hie
why so? exams made your head go crazy
working on a Pokemon bot ( yes the one I was making pokeapi wrapper for)
ah so canary?
irl reasons, and no I'm chilled about exams
Canary?
ah nice
a bot to test the wrapper but it seems like you made a wrapper for a bot
yea I'm doing quite the opposite of what one should do
yes you are
I thought there was, with from itertools import cycle and status = cycle
What else did I send?
!d itertools.cycle status
itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
```py
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
```...
itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
```py
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
```...
ok yeah
#bot-commands
same thing no matter what
@bot.command()
@commands.has_role(894035256129232937)
@commands.has_role(780648554271211542)```can i have 2 roles?
Reason for that is I don't want to make api reqs inside the command itself, so solution for that would be creating functions, and now since there would be many functions ( around 50+) so I'll make it in a wrapper itself
put a comma i think
yes but use the decorator that takes a list
has_any_role
? wdym
@bot.command()
@commands.has_role(894035256129232937,80648554271211542)
otherwise try or instead of comma
@commands.has_any_role(1,2)
yeah not making a request for each command and making a actual api wrapper sounds like a good idea
okay i'll try these things out! thanks yall
:)
this deco lol
Currently I just made a json file with data from somerandomapi.ml , but I'll be updating stuff soon
so I wouldn't have to use dictionary keys for everything and objects instead
why exactly?
https://github.com/sarthak-py/PokeMare/blob/main/data/pokemons.json this is the minimal data
Around 5% of what I'll actually need
And I tried making json for all the data from pokeapi.co (only Pokemons) it exceeds 70 mbs
so your having a db and not cache?
so its more like methods to access the db?
I wont be Changing it so yea
I mean, that's just for reading purpose
ah ic, so this is all for a bot?
and it's for the bot, the api wrapper has cache
Yep
so much things to do for just a bot
Thinking about doing yu-gi-oh, Beyblade or some shit
Well the wrapper could be use anywhere not only the bot xd
maybe a marin bot🏃
¯_(ツ)_/¯
never seen one been made
Leaning towards Beyblade since the concept seems very interesting. Allowing people to collect different bey parts that they can integrate into their bey and allowing them to battle with others.
how would they battle?
Same way you’d battle with a pokemon bot
could use video manipulation
Oh fuck no.
Api reqs go brrrrr
and show the actual beyblades of the users never seen that one done before
That’s would be extremely difficult to integrate.
nvm, how would you make it say Live on YouTube, not Live on Twitch?
but unique is that not what youre trying to do?
discord.Activities.Streaming(name=...
not sure if you can tbh
activity=discord.Streaming(name=StreamName, url=Streams))
I made 3 views for a slash command ( to be edited in a single command) and don't wanna read the code again
hi need a bit of help
'function' object has no attribute 'start'
im tryna dynamically create a task but it keeps making it a function, and i dont want that since it wont start the task
the_task = tasks.loop(seconds=30.0,loop=plant_growth)
this is my function im tryna do
async def plant_growth(self,ctx,trayid,number):
and the part where its meant to run this spaghetti code
the_task.start(self, ctx, trayid, number)
help
maybe watching?
yeah it is but it has so much potential thats not being implemented?
such a unique idea thats being limited no?
shouldnt you go all out?
I’m not trying to break my back over something so trivial.
Maybe img manip
That’s as far as I’ll go
well then dont start which such an idea?
ive tried all i could but still couldnt get it to work
your unique idea will get taken away and made in to something better if you dont make the general features of the game
Okimii I already had plans in mind. What you're suggesting poses extreme difficulty towards the development.
And that would be the flow of how all discord bots works
Functionality comes first. UX comes later.
your discord bot will be limited to the show then? beyblades are about action and pure fighting and making it an img doesnt seem quite cool seems like its just gonna be a boring old bot for all beyblade players since they actually cant see theyre own beyblades fight and get there blood pumping
tasks.loop is a decorator
yeah but having such a bot that cant get better cant really get taken away from you
You get the same experience with pokemon bots yet people still dig those
then what do i need to do
ive really never used tasks like this before
yeah but they will always be that one bot thats better than all of those so why not make yours the one that started it all and is the best one
@tasks.loop()
async def some_function ():
...
some_function.start()```
Because in the end someone will find a way to one up the bot
i want to make a background task dynamically
Being the original is good enough for me
then make it so good you cannot one up it thats the goal no?
No because that’s not a thing you can doc
so i can have 1-2 background tasks for some shit and im too much of a lazy person to make it check and update all the plants itself
Software is always being one upped
There’s never gonna be something at the top
And just stays there
then youre limiting such a good idea nothing can limit the bot but just you?
some software can be one upped but its not really ran by one person so it will be hard to make everything come true
I have no idea what you just said okimii.
@slate swan that possible?
With what I said tho.
You can continue to try to strive to the top
Continuous development
I’m not just gonna release the bot and stop there.
Yea you can do that with a task
Sarthak back me up here please.
just as the example I showed above
wait really?
most ideas go to the team that does the software but most wont get approved because its not one person thats making the decisions
when i tried doing that it would only run it once
🙃 I myself started with 2-3 bots and never completed it lol
But now since I have someone else working with me too, I may be consistent this time
but making a bot thats so limiting that it limits the show itself makes it look like the developer of it never thought about it well or were limited by themselves
It depends person to person
take discord.py as an example 🏃 danny made discord.py as the sole maintainer
And then py-ahem library , a bunch of Devs with a low success rate
@bot.event
async def on_message(message):
if message == "Hey":
print(f"Hey")
else:
pass
```Is this correct?
yes it's correct, syntax wise
Why do you need partial messagable?
this code is not working, what is wrong?
@client.command(name='email')
async def enviar_email(ctx, membro, *, mensagem):
member = ctx.author
data_entrada = member.joined_at.strftime("%b %d, %Y")
if data_entrada < datetime.timedelta(days=7):
await ctx.reply('**OPS** | Você precisa ter esta conta ({1}) dentro do servidor a mais de `1 semana` para executar este comando. :confused:'.format(ctx.author.name), mention_author=False)
else: pass
await ctx.send(f'{mensagem}\n\n~ enviado por {ctx.author.mention} para {membro}')
reinstall discord.py
@slate swan
RuntimeError: Task is already launched and is not completed.
i tried running the task twice for 2 diff plants
it did run the task
but only once before displaying this error
3 times actually
@tasks.loop(seconds=10.0)
async def plant_growth(self,ctx,trayid,number):
...
plant_growth.start(self,ctx,trayid,number)
async def hydrotray(self, ctx,number,trayid):
if plt.endswith("Plant"):
try:
plant_growth.start(self, ctx, trayid, number)
except Exception as e:
await ctx.send(f"ERROR: {e}")
else:
return
the hydrotray is a function that is meant to shorten the command
can anyone help me?
both the function and loop are very long so i only highligted the important parts
Timestamp markdown is not supported on mobile?
membro in your params i presum is to be spelt as member
Calling the function inside the function itself?
no
They are, but some of formats won't work
<t:time:f> works or not?
no, in i typed it in portuguese just for differentiate the other 'member'
like i said hydrotray is a function inside a bot command like
@bot.command()
async def yadada(ctx, number, trayid):
await hydrotray(ctx, 1, tray1))
Actually then which one works for mobile also?
did you get any error
the CommandInvokeError
let's check
!e py from datetime import datetime print("<t:",datetime.now().timestamp(),":f>")
how can i make it so that a bot event get's turned into a function whenever it's called in the code? def choice(): @bot.event async def example():
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<t: 1644954043.963345 :f>
It's already a function, why change it again
<t:1644954043:f>
@spring flax
<t:1644954043.963345:f>
<t:1644954043:f>
