#discord-bots
1 messages · Page 1080 of 1
try and reach a deal with some big server moderators so they add your bot in their server
Yeah that could work. Contact big servers related to my target audience and when they add it people might see it and add it
To twitter!
look for servers who are willing to disboard list and stuff
servers who have tags for your target audience
@flint isle do you host your bot somewhere?
no not yet
If you want to, go ahead
that means i is not an iterable here
print i
there are changes in 2.0
other wise it wouldn't be called 2.0
from what i saw yesterday most iterator or functions returning list before have become async generators
so u have to iterate using
async for i in list:
print(i)
Does anyone know how to create embed with this:
{content: This is the content part}{embed}{title: This is the embed title}$v{description: This is an embed description}$v{url: https://discord.gg}$v{author: Author Name && https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024 && https://discord.gg}$v{field: This is the field title && This is the field description && true}$v{thumbnail: https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{image: https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{footer: This is the footer && https://cdn.discordapp.com/icons/980316232341389413/205c8c67f07e1bd41c186533e9de4f01.png?size=1024}$v{color: #0062ff}$v{button: This is a button && https://discord.gg}
The output is this:
https://tokyotokyotokyotokyo.tokyo/
(it's basically an embed builder so people can do custom embeds for certain things)
u have to parse this and add the data to your embed field?
even w code like that
so how do people add this data for their embed
https://leovoel.github.io/embed-visualizer/
ask your users to create an embed with it and use Embed.from_dict
the way you are trying to do it requires good knowledge of regex and logics
need command ideas...
do pls help in dank
😂
voice recording
🥱 mee6 does that + who tf uses that
u people read manga?
only when i want to spoil their anime~
lmao
same as Sarthak, just to spoil the anime my friends are watching at the time
lmao all bad people giving spoilers
make a command that bans anyone that says "i love you"
you just said it 😔 plus whats wrong with it
gets banned , im petty
fine
fair enough
||Don't give spoilers
||
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Ok but like if i start the giveaway the time that giveaway will end
Not the <t:7373836:R>

...?
how does that relate?
Like if i start a giveaway for 1 min so what i have to do to get ends in 1min? I have to add something in it?
no? just set the style to R
There are integers in it like <t:738272:R>
you pass in a datetime object to the format_dt function, rest is handled by dpy
Guys do owners of python discord change avater of server daily or they have a system in their bot?
If there is system in @unkempt canyon can anyone tell me I would i like to make it in my bot
It's only changed for events
Or for specific months or days
The bot repo is public but I have a feel you'd get lost there easily
Can we change it using bot?
Check Google to see if it's possible not to copy code
But me will search GitHub
!src
Yes you will
I searched for eval command but very confused
I got this code
await bot.edit_server(ctx.message.server, icon=None)
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.
Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned...
Docs have it all my friend
how did ur chem go?
nice
OoO happens first times for everything
Thankfully I don't need the subject since I've been teaching myself all this time
class bytes([source[, encoding[, errors]]])```
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a `b` prefix is added:
• Single quotes: `b'still allows embedded "double" quotes'`
• Double quotes: `b"still allows embedded 'single' quotes"`
• Triple quoted: `b'''3 single quotes'''`, `b"""3 double quotes"""`
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence...
Math is easy pesy
try calculus
Is it math library for py?
no, i mean the calculus branch of mathematics
Oh
it's not like one branch is easier one branch is tougher if u go to a certain depth in any branch it gets tougher
well i find it tougher than others..
hmm true
!src
Guys how can we make that if we react to message with bin emoji like @unkempt canyon then it deleates message
Can anyone help me?
You can wait for reaction
Hmm?
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Check also?
Check is functiin
Ik
Not only for message
Do you know how to make documentation search command?
!src d
Look up documentation for Python symbols.
The thing I'm tryna do is with this:
https://embed.wock.club/
it generates the code aswell and this is what I want to try and make, with the $v & the {}'s
It's very confusing on GitHub
Can 1 bot have multiple Names, Avatars?
import discord
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
def check(msg):
return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id
class suggest(commands.Cog):
def __init__(self, bot):
self.bot = bot
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Option 1",emoji="👌",description="This is option 1!"),
discord.SelectOption(label="Option 2",emoji="✨",description="This is option 2!"),
discord.SelectOption(label="Option 3",emoji="🎭",description="This is option 3!")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
class SelectView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(Select())
@commands.command()
@commands.cooldown(1, 43200, commands.BucketType.user)
async def suggest(self, ctx):
await ctx.send("**Type the suggestion you want to submit**")
suggestion = await self.bot.wait_for('message', check=check,timeout=20)
suggestion = str(suggestion)
await ctx.send(suggestion,view=Select())
async def setup(bot):
await bot.add_cog(suggest(bot))
How to fix this error
Make that check inside the command
Ok
why are you putting a class in a class
What
Whats meaning of it?
class A:
class B:
...
class C:
...
Ok
nested classes lol
better make another file for views and import the view objects from that file (recommended) or just create them outside the cog

thx for the example yesterday helped a lot
I'll make classes then only if this poop replit will stop giving such annoying and poop errors
Such errors this ****************** replit gives without any reason
why are u coding on phone?
My laptop with my dad ;-;
why what were u doing on it🧐
I was playing games
Sus

Do you have any solution for it?
for?
That **** replit
idk try and add import discord on top
should name your class with UpperWord and so naming clashing doesnt happen
Ok
if message.guild.id == 123. . .:
Says ‘nonetype’ has to attribute ‘id’
Btw if there is comamnd called >test
And i type >tyst
So i want that my bot send no command called tyst found
How can I do it
guild is None
now your dad's playing?
did you loaded the cog?
Bruh do their work
nice
?
I not mean that
Me want that if there is comamnd called >test
And i type >teyt (wrong spelling)
So my bot should send no command teyt found
How to do that?
error handler
Means what type
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only.
Hey everyone, trying to fetch daily no. of users who message/voice in the server. can you please help how can i do it?
a log?
um, the total number of user per day.
create a database and use the on_message event and the on_voice_state_update event to check
?
can you please help me with an example? i am new with discord dev.
do you know how to work with databases?
Ash could you see above
Hi, I had a problem with replit.com, everything I do says Packag Operation Failed
yes, i am aware with working with db just wanted to know how can i fetch the details
whats time?
Its module?
the numbers
time.time() should return the unix timestamp
and Idts that's the issue, do you have a wait_for?
@slate swan how to fix this error?
Yes
details? aren't you gonna be the one inserting the details instead
wonderful
u can just create a log channel in your main server and send the data when commands are being used there
And get yr bot ratelimited when multiple commands are invoked at the same time!
better use a database, ps they asked about daily users who are active in a server
do they get ratelimited then how do big bots operate?
logging data in channels instead of a database is just unnecessary requests, and most probably large bots don't do that, so there's no point, also, they are verified and have larger number of requests per second compared to unverified bots. Sorting of data in a discord channel can also be much harder as compared to a database that provides enough flexibility for you to organize your data and you could use other stuff to display your data with a more organized layout
no i get the sorting part i am concerned abt the rate limit part
there's no point, why would anyone want a log to be sent to a channel on every message
so some bots use pil
wha-
and u can only send pil images as attachment
example lemme finish
sure
and file attachments cannot be edited
so currently i have a paginated pil images menu
which i send the image on a channel and get url from that image
and use that url in set image before paginating
so i was concerned abt the rate limit part for sending messages in a channel
wdym? like i have 3 pil images
how do i get that in one url
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Send!",emoji="✅",description="Send the suggestion!"),
discord.SelectOption(label="Cancel!",emoji="❌",description="Cancel the suggestion!")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(content=f"Your choice is {self.values[0]}!",ephemeral=True)
Guys i want that if someone click on then it sends message and if ❌ then not
How to?✅
still dont understand, how does it look?
like you got 3 pages with each page containing one image
and that image is set from a url of an image you send in another channel of yours, right?
u wanna see?
i can invite u...
sure
Can anyone help me?
what does self.values[0] send?
discord.py 2.0 dosent have values
it does, smh
i tried ysterday
lemme try
its interaction.data['values']
Anyway I'll remove it
And how can I do that if someone click on green tick the it send something
u have to add a check like if u click this value something will happen
also for this use buttons
not selection drop
I want for selection drop
ok..
if interaction.data['values'][0] == '✅ '
Oh k
something along those lines
@shrewd apex will id of emoji work?
it should
depending on what u are getting in interaction.data
but pretty sure there is a way to make it work
linter dosent give error run and see
have the values
i got error select has not attribute values
select here is a class so it will naturally show no error
uuuhh, I'll have to create a new view and stuff, brb then
uwuView
@shrewd apex
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Send!",emoji="✅",description="Send the suggestion!"),
discord.SelectOption(label="Cancel!",emoji="❌",description="Cancel the suggestion!")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if interaction.data['values'][0] == '✅':
await interaction.response.send_message(content="successfully sent!",ephemeral=True)
It's not working ;-!
print interaction.data
You need a value kwarg in SelectOption
also you don't need interaction.data
if you think about it, you are subclassing Select
so self is Select... do self.values
Hello, devs!
I want to know the best way to localize text in bot's output. At the moment I store all data at .json file
Guys how can we do that if someone select a option from drop down bot sends a dm to a particular user
How to?
like a redirect to a site which supports that?
get user by snowflake and send him a dm
no
How can I do it
documentation
ah
commands.Bot.get_user(id)
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
just label and desc in enough value will default to label name
Using tasks loop slow down the bot's speed?
lmao
it works in the background so negligible difference in speed unless u run some heavy memory consuming task

@client.slash_command(
base_desc='Shows your Wallet Balance',
name="wallet",
options=[
CommandOption(
option_type=discord.Member,
name='member',
description='Mention the user to check their Wallet Balance.',
)],
guild_ids=[])
async def test(interaction: discord.ApplicationCommandInteraction, user: discord.Member=None):
"""Shows your wallet balance."""
if user is not None:
embed = discord.Embed(title="Wallet",description=f"{user.id}")
await interaction.respond(embed=embed)
What is wrong?
Something
Where can i read
import discord
from discord import SlashCommandOption as CommandOption, Permissions
import datetime
what the-
Never installed disnake
Because u are using client
import discord
from discord import SlashCommandOption as CommandOption, Permissions
import datetime
client = discord.Client(sync_commands=True)
@client.slash_command(
base_desc='Shows your Wallet Balance',
name="wallet",
options=[
CommandOption(
option_type=discord.Member,
name='member',
description='Mention the user to check their Wallet Balance.',
)],
guild_ids=[])
async def test(interaction: discord.ApplicationCommandInteraction, user: discord.member=None):
"""Shows your wallet balance."""
if user is not None:
embed = discord.Embed(title="Wallet",description=f"{user.id}")
await interaction.respond(embed=embed)
that isn't even the proper syntax for slashes 😭
Impressive imports 💀
this is how you create app commands for discord - https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
I'm just running the examples from here - https://github.com/mccoderpy/discord.py-message-components/tree/developer
A 'fork' of discord.py library made by Rapptz with implementation of the Discord Message-Components & many other features by mccoderpy - GitHub - mccoderpy/discord.py-messag...
is this not official 😮
no.
sad
Hydro seems like a troll tbh.
They send a message, and if nobody replies, they delete their message. 😏
👀
Im a troll whats ur problem
But at least i help people out there struggling
(if ik how)
Better than those that act like pro but knows nothing
:hides swiftly:
Lol
client.send_message isnt even a thing
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
use this instead
ctx.send()?
Also, the parameter order was switched
wdym
ctx, error is the order
whilst currently, ctx works as the exception raised and error works as the context
Yup
still not working
the first argument should be the content of the message, ctx.send will automatically send it to the channel
Lol i forgot i had on command error already
so there were 2 and it wasnt workin
smh
await ctx.send('You wrote wrong command.')
So its working?
Hello I have a quesiton, how to do you chance colors of block quotes for bots?
hi
like that's grey but how do i make it blue for my bot? ^
U can't @left bolt
How am i able to see for other bots them having blue?
red, yellow?
Mind showing a pic?
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
!d discord.Embed.colour
The colour code of the embed. Aliased to color as well. This can be set during initialisation.
Its hyperlink
U click on it
It will redirect u to a website
How would i make an interactive setup command?
For example,
It will send a message and the user then sends what its asking for such as a role etc.
And it stores that role and moves onto the next message?
Do i need to put it in all comamnds?
its an even like on_message is
?
I am using sqlite3 and i made new db and disk is having enough space still this error
is it hosted on a VPS? seems like they are not allowing to perform write Operation
tf
restarting your project may fix it
K lemmie try
It is not fixed yet
how to update discord to latest version again
the github thing
is this how i install the latest discord.py?
but i only have 1.7.3
async def main():
async with bot:
(await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py"))
await bot.start(os.getenv('TOKEN'))
asyncio.run(main())
yes u install that and unistall the old one
but she say i need 1.8
what 1.8? bot.start is there only in 2.0
python 3.8+
alright
for dpy 2.0
how to uninstall the old one
pip uninstall discord.py==1.7.3
ok
u can unistall calling strong equality
just telling to uninstall since the code may take 1.7.3 as default it's better to work with a cleaner venv
yeah
all good
ok
oo
hi guys, how can i import the created_at to 6days ago or
6 months ago
if the member acc 356days older the bot write 1 year ago..
make a function to do that
ok but i dont know how to start it
hmm
@commands.Cog.listener(name="on_member_remove")
@commands.guild_only()
async def fm(member):
await member.ban(reason="User left while freeloader mode was on.")
user isnt banned on leave
not even the help command?
i removed it
but its printing the we have logged in as blahblah thing
You need to enable message_content intents, it's required for seeing message contents in v2.0
ok

.
do Intents.all()
ok
commands.Bot(..., case_insensitive=True,) instead of having a list of all prefix names
ok
no
sad
lol
it works on commands
what import?
cogs are not loaded?
ya
any errors?
try once again but this time with the for loop properly and print statement in the midlle
?
like print(f"loaded {cog}")
okok
(await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py"))
```how tho
(print(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py"))
wait, i got it
change it to a list comp, its a generator right noew
() this gives an async generator object here
?
[...]
thats why i said to take it out and try
adding an extra line wont kill first lets try with just plain for loop
basically anything inside a generator doesn't get executed unless u iterate over it
we can compress/one liner it later
for file in ...:
if file ...:
await load...('commando....')
for file in os.listdir("commando/"):
if file.endswith(".py"):
await bot.load_extension(f"commando.{file[:-3]}")
print(f"loaded {file}")
its working
i mean the whole bot is working
loaded everything
@shrewd apex @paper sluice
nice
how
cause as far as i remember generator yields the first object and stops
and waits for the call on the next object
its not exactly necessary here tho but u can try by just replacing () with []
👆
[await bot.load_extension(f"commando.{file[:-3]}") for file in os.listdir("commando/") if file.endswith(".py")]
so i do this?
yeah
Any help?
no idea
did it work?
all urls are now avatar.url and icon.url
ok
this worked?
yes
nice
huh? you're using bot.run or bot.start now?
afternoon Lord
3am there?
uh ic
2pm to be specific
hmm
welp back to pil i guess for me i hate finding co ordinates on image to paste such a chore
pil is blocking 😔 make sure to run them in the loop executor
Possible to do like
If the user uses a?truth (mentions a user) and the bot returns {ctx.author.mention} asked (the user mentioned after a?truth)
async functions are not enough?
No, cause async function doesn't handle blocking code
It just allows you to run that function as a task and asynchronously
Yes, why not
async doesn't magically make something asynchronous :)
so how to run them in executor
how?
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
spawn a thread and run the blocking code there
pass None to the executor
import discord
from discord.ext import commands
from replit import db
import asyncio
db["likes"] = "test"
if db["likes"] == "test":
db["likes"] = 0
class vote(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def vote(self, ctx):
await ctx.send("voting..... ")
await asyncio.sleep(2)
like = int(db["likes"]+1)
db["likes"] = like
await ctx.send(f"successfully vpted! we have {like} votes now")
async def setup(bot):
await bot.add_cog(vote(bot))
Guys my command is not working and even it's not showing any error
Can anyone help me?
What do you have currently?
so currently i have my pil in an async function and it returns the image which i use in the code
What discord.py version are you in? If it's v2.0 then you need to enable message_content intents
you could use the bot's ongoing loop
bot_instance.loop.run_in_executor(None, sync_function)```
ok
Nothing
I came here to ask for it
I ahve enabled all intents
lemme try
so i have to run them in executor everytime calling the function?
Don't show screenshot, paste the code here, we can't see if you passed the intents correctly to your bot instance
ok cool lemme do that
asyncio.get_event_loop().run_until_complete(func())```
is another alternative but wont recommend it
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=">", intents=intents)
what's the issue
Commands not triggering as usual
all commands?
@robust fulcrum do you have on_message event?
not sure, but I think so
It's command ;-;
xCirno#0001
async def _(ctx, commands.Context, member: discord.Member):
...
you can use the mention property now
member.mention?
yes
Ty
just a single command?
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#parameters this can also help you in the future @slate swan
Isn’t that for coros
they were making coros so thats why i wrote that out
do you have an on_message event?
ok so as i said i have the pil in an async function so will that run with bot.loop?
You would need to use run_in_executor (or asyncio.to_thread) on the pil functions within the async function
^
async def image(parameters):
#pil stuff
# return image
#in bot
foo = ___
async def open_image():
im = await bot.loop.run_in_executor(None, Image.open("_.png"))
return im
#command
await open_image()
member is not defined
foo is where i call the function
wait what?
see my example above ^
It should be awaited
ok so i need to only make the image open part run in executor or every single pil line
Ye
Wha it's a comamd bro
@commands.command()
async def truth(self, ctx, member: discord.Member):
tEmbed = discord.Embed(titlle=f"{ctx.author.name} asked {member.name}", description=random.choice(truth), color = discord.Colour.dark_theme())
tEmbed.set_footer("More truths will be added in future.")
``` code ^
yeah sorry
could you should the whole traceback?
🙂 doesn't answer my question
Not really, just create a sync function for your pil code, and then run that function in a thread/executor
There is no error because I didn’t run the bot
You not understand me
then how isn't member defined...
The member is underlined in the code
ide issue
restart the IDE
hmm that's prolly the best bet ig thing is already have the function defined in async and i use a lot of async elements in it like aiohttp
Why would I put on_message in a command ;-;
so it's tough to make the function sync
why don't you just answer his question? hes asking cuz an on_message event blocks commands from working
bro, nobody asked about your command, everything out of context, do you have an on_message event?
Ahh, thats too bad, you should run it in executor on every PIL function then
i didn't ask in a command, im asking if you have an on_message event
uh, commands don't work magically
they use on_message events to function
so if you mess with it , any of your commands won't respond
🥲
Me not able to understand what you all asking
sad me
if i use requests.get instead of aiohttp will that work too with bot.loop?
Do you have any events named on_message any where in all of ur code?
Nah me not use on_message
@client.event
async def on_message(message):
...
or
@commands.Cog.listener()
async def on_message(self, message):
...
is there something like this in your code?
No
sure, why not
It probably will but it’s probably slower and other things
@robust fulcrum can you send your main bot file
Ok
@slate swan ^
Well, yea it will, but can't you just seperate aiohttp methods with pil methods?
which version is reccomended to be a database for a discord bot?
oof so bot.loop is faster everywhere?
restart vs code
potgresql
@slate swan do you have replit I'll send multiplayer link?
i use mysql but will suggest pgsql
ok
but to make a req in that pil function won't i still have to await it
i can't open a browser tab rn, so pls send it here it you can
can someone get me the embed link?
mysql and postgres are both great
unless i call that function before and send data as parameters
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
thankss
bot.loop.run_in_executir runs in a seperate thread so you don’t want to use it when you don’t need to
which version should i use... should i use 14
so request.get seems only option rn how much slower do u think it will get
!paste
Why 2 color and colour 🤨
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.
alias
cause people have their own preferences of spellings
ohk
americans say color, britishers say colour
@slate swan https://paste.pythondiscord.com/pacetitoce
brithshers
because its color 🤣
💀
😅
americaners
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Main.py", line 2, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)```
Not sure but you can use await bot.loop.run_in_executor in an async function with aiohttp
same....
🤣
Someone
and when you use the help command nothing shows up?
interesting
lol
how ?
yes, but I meant can't you do something like this:
def pil_func(arg):
# do pil stuff here
async def make_request():
async with aiohttp.ClientSession() as s:
r = await s.request(...)
run_in_executor(None, pil_func, r)
``` or something
english is from england and england is in Great Britan so "britishers" english is always the correct one
lol
Yeah but you need to do it on every PIL line then
Yeah that’s not good
discord.py is not installed in a place that your current python can find. did you forget it? or did you just install the bot in a venv and forget to activate it first?
not really just create a whole function that deals with repeated stuff and run that function in executor instead
amercan?
lol
🤣
no i have discord module installed
btw this is correct right?
yes, but maybe not where you thought it was installed
sick description
works, yes
formatted well, no
Yea that's what I'm wanting them to do
ctx.author.display_name or ctx.author.display.name
I have this installed discord.py==1.7.3
First
its general
its display_name
so i just copy paste this and started modifying it
ok, so pip show discord.py confirms the current python can find it?
Name: discord.py
Version: 1.7.3
Summary: A Python wrapper for the Discord API
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: MIT
Location: c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages
Requires: aiohttp
Required-by: discord, discord-ext-bot, discord-ext-ipc```
how do you start the bot? are you sure it uses the same python that pip does?
maybe you have multiple versions of python installed?
yeah, that's what i'm thinking
wait wth is discord-ext-bot, these packages mess with the library iternals
!pip discord-ext-bot
An package for discord.py.
Would you like me to show the extentions that i have installed?
yeah thats the issue
oof
this library if forcing you to use ```py
from discord.ext import bot
bot = bot.Bot()
start with deleting the useless 3rd party libraries.
My trust was just uptil
Meaning?
and
meaning sloppy grammar and "no longer maintained" doesn't exactly recommend these packages to you
just use discord.py directly
if you're following someone's outdated tutorial to make a bot with these, just don't.
discord.py itself has excellent doc.
place = await bot.loop.run_in_executor(None, image(kwargs))
def image(kwargs):
#pil stuff
#returns a tuple
Error
TypeError: 'tuple' object is not callable
dont call the function
no i mean discord-ext-bot doesn't offer anything which 1.7.3 doesn't have
what do i do then?
!d functools.partial
functools.partial(func, /, *args, **keywords)```
Return a new [partial object](https://docs.python.org/3/library/functools.html#partial-objects) which when called will behave like *func* called with the positional arguments *args* and keyword arguments *keywords*. If more arguments are supplied to the call, they are appended to *args*. If additional keyword arguments are supplied, they extend and override *keywords*. Roughly equivalent to:
```py
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
could u elaborate?
it means discord-ext-bot requires discord
Required-by: discord, discord-ext-bot, discord-ext-ipc
!e
from functools import partial
def call(func):
return func()
def foo(a, b, c):
print(a, b, c)
return 1
print(call(partial(foo, 1, 2, 3)))
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
001 | 1 2 3
002 | 1
await bot.loop.run_in_executor(None, functools.partial(image, **kwargs))
that library is quite pointless too lmao
ok thx lemme try
I'll say no more
oh i didn't read that message
partial takes the function and the args, then call calls partial which returns the function with filling the arguments then call can do foo() without having to fill the args
btw ash i was looking into Darker's repo
why you do this? 😔
https://github.com/Dark-Light007/Darker/blob/main/extensions/Admin.py#L4-L7
extensions/Admin.py lines 4 to 7
class Admin(lightbulb.Plugin):
def __init__(self):
self.bot: lightbulb.BotApp
super().__init__(name="Admin Commands", description="Bot Admin Commands")```
It shows up
probably good to confirm what @jade tartan is trying to accomplish, anyway. the discord-ext-ipc extension looks like something to communicate between a client (e.g. webapp) and the bot via RPC. so if the problem is the extensions are interfering (which we haven't confirmed yet), then simply dropping the extensions is not a whole solution. edit: oh, except others have suggested only to drop discord-ext-bot, which i agree with. maybe you can keep the ipc one, though my concern is that it's discontinued so might also give you trouble
well seems like a issue inside your command functions then
It started working now
Idk how
i mean the subclassing part, you can just do ```py
plugin = lightbulb.Plugin("name", "description")
ok so it worked first thanks for that
now i made image an async function it gave me a coro back and i awaited that coro and i got the result i wanted
so is it possible that this work even if the function is not sync?
😔 is it even worth checking out, Its shitty asf
and I just find it better, I know you can just plugin = lightbulb.Plugin(...)
place = await bot.loop.run_in_executor(None, parital(image, x, y, z))# gave back a coro
place = await place # i got the desired result
async def image(kwargs):
#pil stuff
#returns a tuple
me does that because i annotate Plugin.bot with my custom bot class so that Vscode gives me proper autocompletes
umm @visual island @paper sluice any idea if i am doing something i am not supposed to here?
ya u just dont await it
when its sync
so bot.loop work with async as well i dont need to change my function?
bot.loop is an asyncio.loop itself
You have awaited it, you don't await twice
smort, but ig, I'm just too lazy to edit it all now, considering the fact, that I just stopped with discord bots lol
yeah but here image is an async function and when i printed place the first time i got back a coro
when i awaited it again i got what i wanted
oh, makes sense
am still wasting my time writing bots
bots which nobody's gonna use?
help me ;-;
exactly, thats y the wasting part
Umm, you normally don't use executor for an async function though
😔
im trying to promote my bot
so it works ig this way pil wont block?
nice
but every single community server out there: NO ADVERTISING
atleast i can use it for evals to annoy my friends lol
ooof
add it on botlists
pretty helpful
i added it on top.gg
even tho people won't use it, but the server count will keep increasing
its stuck in 100
im not 16 yet
im december boi
;-;
umm anything to add sarth will this work?
someone asked me to make an 8ball command for my bot, so i started making it today. however, apparently the question arg cannot be used alongside .endswith, how would i fix this?
@commands.command(name="eightballball", aliases=["8ball"])
async def eightball(self, ctx: commands.Context, *, question=None):
if question.endswith("?"):
await ctx.send("Question mark detected.")
elif question == None:
await ctx.send("Please include a question in your command.")
else:
await ctx.reply("No question detected. Make sure to add a question mark to the end of your command.")
🏌️♀️ so you can't get it added to more servers too L
help ;-;
is it already loaded?
no
any way to do this in one line?
place = await bot.loop.run_in_executor(None, partial(posi, x, y, 'pad'))
place = await place
if posi is a sync function, u dont even need the second line
@commands.command(name="eightballball", aliases=["8ball"])
async def eightball(self, ctx: commands.Context, *, question=None):
if not question:
return await ctx.reply("not uwu")
if question.endswith("?"):
return await ctx.reply("uwu")
uwu
but it isnt 🥲
🤣
then why running in executor?
and i dont want to go around changing all my functions again it has pil in it
semi colons and your variable naming lol
the thing is PIL is blocking, making the function which does pil stuff async wont change anything
wha-? adding an s to the end of question will only give me 2 errors
yeah lmao i just name randomly
someone told me to run in an executor
that is why we recommeneded executor, so that u run that sync code which does pil in there
it creates a thread...
just remove the async keyword, u dont need it in this case
why run a function in a thread tho?
blockin
yeah so exeuctor here apparently runs async too and gives back a coro which i awaited and got the result
just use a Task?
I've tested it and doesn't seem to work well with async functions
questions.endswith will only give me an extra error. i cant use .endswith with an arg bcs it gives me an error, how do i work around this
from discord.ext import commands
import discord
class Trade(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def farm(self, ctx):
embed = discord.Embed(
description = f'''
.........
''',
color = discord.Color.blue())
embed.set_thumbnail(url = ctx.author.avatar.url)
embed.set_author(name= f"{ctx.author.display_name}'s trade",
icon_url = ctx.author.avatar.url)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Trade(bot))
is this correct?
i have aiohttp in some of the pil so i cant make them sync without changing the whole function
umm i need it for my commands?
typehint, question with str
Guys is there any image recognisation library in python?
like what goes wrong?
well, u can do await (await bot.loop.run_in_executor(...))
question: str=None?
Huh why two awaits?
yes
This is the result with async functions
still doesnt work
the executor returns a coro
error?
and this is with a sync func
in this case
still says .endswith doesnt work
show traceback
Traceback (most recent call last):
File "/home/runner/Yggdrasil-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Yggdrasil-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Yggdrasil-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'endswith'
question is None...
i need to make it optional?
code?
do u want to do anything special when its None?
yes
like?
you have to keep the conditional that checks question is None at the top, iirc it was the 2nd conditional instead, and you were checking it after checking if the question endswith a question mark
like send a different message?
@fallow mauve ^
that's the issue
do this
async def ...(..., question: str | None = None):
if question is None:
...
return
rest of the code
💀
you can also do this 
should use return annotations and you should do if ... is None:
Hey, sorry for dropping in
is https://discordpy.readthedocs.io/en/stable/api.html up to date? I don't find anything regarding community events in it
return annotations? I just copied what was written instead
and yes, that
nested
@slate swan @paper sluice got it to work thx for the help
thank Ryuga
It's the stable branch (v1.7.3) and won't get any update again, the updated branch is https://discordpy.readthedocs.io/en/latest/api.html
return annotations by
def okimii() -> str:
return "El gato!"
which it just shows what the function can return
!pep 484
I know what return annotations are, the hell
then dont be confusing
ash being confused is persistent
Most of the time, I don't even know what I write
🛌
wish
sry accidentally pinged
its okay
its not a coroutine
all the loading functions are now async, await it as the error says
but where =.=
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(...(bot))
yeah it needs to be a coroutine object so you can await it because since it was a function it just returned None which you then awaited
should be async
async def*
ok
why do I always get ignored even after giving a full-fleshed example which are wrong 75% of the times
Hia, i'm trynna set a variable bot's latency, but i'm getting NaN type....
it hasnt connected to the ws yet
i just saw the await down there
What is ws?
didnt see the async up there
websocket
.<
Ah
smort
Well, how can i make a command like ping command but without gettin' NaN type?
It shouldn't return NaN
ping ms?
Yes
oh yeah it can
self.latency = float(self.hb or "Nan")
``` dpy does something like this
@bot.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def ping(self, ctx):
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
You're seeing bot.latency in a command?
its returning None because it hasnt connected to the ws yet😅
I've already a ping command. I'm just trynna make a command that command makes set ping variable and uses it.
@scarlet sorrel send text as file
yeah, you can't access it if the bot isn't connected yet
the value of ping is never constant + why would you want it to be
yeah the latency is always dynamic
ping + ping = ping pong
Just like that:
ping = bot.latency*1000
if ping > 100:
.....("good")
.....
Should i add
@bot.command() decorator
???
you cant do it outside a function invoked before the bot is running
Bot is already running....
you would need to use it in an async function and then just use wait_until_ready
show code
if statements? complex?
ill show you ```py
bot = commands.Bot()
ping = bot.latency*1000
if ping > 100:
.....("good")
.....
bot.run()
why would you paste all of your code
(I said, that code so complex and you can't read it probably
Then you should wait a bit, cus so complex
... that part is not in the file...
@devout iris
from discord.ext import commands
import discord
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="uwu", intents=intents)
@bot.command()
async def ping(ctx: commands.Context) -> None:
await ctx.send(f"{bot.latency*1000}")
bot.run("TOKEN")
What is that? I didn't understand
ash using return annotations 😳
tf is a f string doing there
uh I was adding text with it first, then removed it
😔 makes sense
yeah give her a break shes using return annotations 
👀
smh, I use them most of the times but anyways
Wish I never saw that
i don't see why return annotations matter for a bot command... its not like it will speed up the code or you'll be calling that function elsewhere
same, that's why i dont add them too
just good practice
ew
🚶♂️ when you realise my top played song on spotify is the same
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def trade(self, ctx, arg):
```arg is string by default right?
yes
ok
50 commands in one day is nothing compared to the amount I text on Instagram per day 😔
me wondering how ppl even do that
both 50 commands & texting thing
ryuga 👍
I always have somebody new DMing everyday, so that's a thing
sad woman noises
but i dont get any
i just check my insta for cat memes
🤣
Might as well take this to OT
👍

why you killing the chat like this
You're welcome
thank you
polite
ew
@vote.error
async def vote_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Cooldown you cant vote yet!",description=f"Try again in {error.retry_after:.2f}s.", color=discord.Color.red())
await ctx.send(embed=em)
Guys is this error handler correct?
no
Is () missing?
you didn't put
else: raise error
Where I have ti put else?
after the if
Oh k
what kinda question was that
And do i need to put ()?
no
I was knowing just brain stop working ;-;
@heady sluice is there any library to covert seconds into minutes?
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
its just seconds // 60
or that
just divide it by 60
Divide
ah /
Multiply will do into milliseconds
you would multiply by 1000
Anyways just i would go for simple
mille means 1000
import datetime
formatted_time = str(datetime.timedelta(seconds=num_of_seconds))
print(formatted_time)
megaew
!e
import datetime
print(str(datetime.timedelta(seconds=70-1)))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0:01:09
could you just stop instead...
no
@slate swan i have a variable {error.retry_after:.2f} how can I put it into formated_time varibable?
ask meh, he's better
@heady sluice can you tell me?
But his Brian smol I may broke it
print it and show results
meh decorator 
also print type
?
now what
it'll return the remaining number of seconds with 2 decimal places
Why print i want to just put in variable
oh my nickname
well then isn't it obvious
what
where to put it
well, help him then
@vote.error
async def vote_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Cooldown you cant vote yet!",description=f"Try again in {error.retry_after:.2f}s.", color=discord.Color.red())
await ctx.send(embed=em)
else:
raise error
I just want to replace {error.retry_after:.2f} into a variable
I'm trying to send multiple images from a sqlite database using a simple plugin, problem is it always sends the links then the images afterward, anyone know how to simply hide the urls so only the images are visible?
import datetime
hello = str(datetime.timedelta(seconds=error.retry_after:.2f))
