#discord-bots
1 messages · Page 715 of 1
Of course
dont use json tho
or im going to go crazy
haha alright
Hello! I need someone to help me with this command.
So basically, you run !trade command. And then the bot sends you two questions in DM; what you wanna trade, and what are you trading for.
So when you fill those up,
the bot sends return message in the channel choosed.
For example it says;
@amber beacon want to trade!
Trading: message 1
For: message 2
since youll need a db
use temporary variables
pardon?
Structured query language
Bruh-
I explained everything?
you want it to wait for a msg?
my brain is hurting rn
leaves, bye then, extra smort guy
Can I explain you?
got bored of it
no you cant explain me
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
thats the language youll need a db tho
thats async
SQL is easy although the schema is tough
im looking forward to this
i quit because it was boring
thats nice
just lying to myself i can feel the pain coming
i will jump to sql when i finish my 300functions

pretty easy ngl
Me quit discord bots because they were boring...

im about to do the same
maybe just to making wrappers
@slate swan DMs bud
looks easy
Exactly
I just randomly stroll here help someone and go back
Lol same
if 'afk check' in message.content:
print('i have been summoned')
await message.channel.send('Hello')
else:
pass
``` is this correct?
Depends
Syntax is by far correct
TypeError: on_ready() missing 1 required positional argument: 'message'
on_ready doesn't take any params
Yes although you have to use async version like aiosqlite
Ok thanks
I think it has something to do with discord
would anyone like to also code with me on this discord bot:D
how do i make spaces in an embed(new lines)
im down to contribute
\n
thanks
makes a new line
Bro on_afkcheck isn't an event
sure
i forgot
thats nice i can learn sql and use it
You have to use on_message
alright bet
Also you can use SQL if your bot is supposed to be a small one. Otherwise you will need to use PostgreSQL
Postgre is a beast
pg uses sql
sql isnt a db its a language
Syntax is somewhat different
ofc it will lol

send me the repo when you can
i have to finish my 300functions first tho😔
embed.set_image(guild.icon_url)
TypeError: set_image() takes 1 positional argument but 2 were given
how is this 2 arguements 😔
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
is sublime text good?
and what is the *
That's why you're extra smart
makes every arg after a kwarg
ofc
i only use json to hide my token
vsc is good
i use vsc
just put null?
why is the bracket red? @slate swan
pycharm takes 1gb of ram for me
Leave that, pretend it doesnt exist
needs to be a str
oh ty
for what?
.
i have this at the end of my code, but it doesnt print "online!"
economy bot
😔
print online is after running the bot 💀
Sureeee
brain fart
No code is gonna run after bot.run since that function creates an endless loop
you have to make a on ready event
so like @on_ready()
@client.event
async def on_ready():
ctypes.windll.kernel32.SetConsoleTitleW(f"Anti AFK • Ready as {client.user}")
print(f'Logged in as {client.user}')
print(f'Logged in as {client.user}') isn't printing out anything kekw
yes
im not sure im new to coding
I advice you to learn python first since making discord bots is a task for higher level developers
Error:
Traceback (most recent call last):
File "C:\Users\W 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\W 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\W 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'to_dict'```
Code:
```py
import discord
from discord import colour
from discord.ext import commands # This is the part of discord.py that helps us build bots
token = ''
bot = commands.Bot(command_prefix="-")
@bot.command(name="hello")
async def hello_world(ctx: commands.Context):
await ctx.send(embed=discord.Embed(description = "hello", title = "Test yay!", footer = "ok!"))
@bot.command(name="ping")
async def ping(ctx: commands.Context):
await ctx.send(embed = discord.Embed(description=f"Pong! {round(bot.latency * 1000)}ms", colour=0x2f3136))
emb = 'discord.Embed(title = **__Level Rewards__** :giveaway:,description = > test \n ok, colour=0x2f3136)'
@bot.command(name="level")
async def ping(ctx: commands.Context):
await ctx.send(embed =emb)
bot.run(token)
print("online!")```
Try commenting the third line
i was told to look at https://tutorial.vcokltfre.dev/
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.
still, doesn't return anything
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Look at these first
Even the embed initiator is inside an str welp
you dont make a embed obj a str😭
Your output and code pls
how can i fix the error still?
dont set a img?
bruh
;-; i literally gave you the answer
why would you set an img if your not gonna send one?
hurts my brain
fixed
what?
lol
why are you setting an img and not setting an img?
Bro URL is a kwarg
you mean this?
guild = bot.get_guild(guildID)
embed = discord.Embed(
title=guild.name
)
embed.set_image(guild.icon_url)
embed.set_footer(text=f'Owner: {await bot.fetch_user(guild.owner_id)}')
await message.channel.send(embed=embed)
^
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
basic py lol
no comments
why even set an img with the embed var and not the embed constructor
coughs
😭
Isn't that the only way 
haha no
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, 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.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
Oh my god, what are you
why is the * there?
a newbie
makes all args after a kwarg
ARG means argument and jwargean keyword argument
it used to be here but i cant find it anymore
is it compulsory?
God you need to kill the terminal
Hub, restarting vsc means, closing and opening it again
pardon?
Mhm, yeah, that works too
Yeah, cant argue
do i need to have it therE?
yes
where
ikr
How many time has that message been mentioned 🤣
In vsc
more than the functions i have to do maybe
Lol
afk_check_messages = ['Afk check', 'afk check', 'AFK CHECK']
how do i make a function so it goes through every single string in the list?
Lol
a for loop?
Or any()
no
iteration, love, iteration
Well for loop is better here
yes
so why guild.icon_url is not icon url
for iterable in afk_check_messages:
Icon_url returns none if the guild has default icon
My dear Big big brain
embed.set_image(url="whatever")
And no joke
big?

Humor, love, humor
ikr
!ot
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
how do i split it with the message sent by the user?
i thought it was message.content.split(“::”)
Ye it's the side effects of a tutorial
💀
how do i grab the guild from message?
@slate swan im not even done yet
anyone know why user is underlined?
my small brain needs assistance
typo
oh.
users as you set in the var
yeah
@bot.command(name="split")
async def split(ctx: commands.Context):
await ctx.send(message.content.split(“::”))```
You defined users instead of user lol
LMAO
it might be because of a typo or something that is misreferenced.
how do i grab the guild from message?
i think its
ctx.guild
not sure
what do you mean? grab the guild from the message object or?
vsc us saying it ?
!d discord.Message.guild
The guild that the message belongs to, if applicable.
typo again?
that might be what you are looking for
yes in vsc
check the place where you are referencing the object, could most likely be a misreference or a typo

Those are some weird quotes
anyone here have anything more advanced to add to a moderation bot?
ctrl c
just closed my bot and it was playing relaxing music
i need something challenging to keep my interest
reason = ""
while reason == "":
if reaction.emoji == "0️⃣":
reason = "Other"
break
elif reaction.emoji == "1️⃣":
reason = "Too short application \ poorly explained"
break
elif reaction.emoji == "2️⃣":
reason = "Lack of hours on Unturned \ inexperienced"
break
elif reaction.emoji == "3️⃣":
reason = "Bad english \ grammar"
elif reaction.emoji == "4️⃣":
reason = "Inactivity \ Lack of hours on ICE RP"
elif reaction.emoji == "5️⃣":
reason = "Too many incorrect answers"
elif reaction.emoji == "6️⃣":
reason = "Lack of developer skills"
elif reaction.emoji == "7️⃣":
reason = "Cannot be trusted \ too many bans"
elif reaction.emoji == "8️⃣":
reason = "Troll application"
embed.add_field(name="Reason for denial", value=reason, inline=True)
await chl2.send(content=None, embed=embed)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required
woah
someone gave it to me
that's a lot of if and elif checks
not very pythonic if you ask me
why?
get the channel?
ok they do convert back to standard ones
and interactions are autistic
lol
cant
not really
Why not create a dict?
some dude literally said its impossible
@slate swan
welp first off, message isn't there....
there's no variable called message anywhere
so how do i get the message
that's an interesting way to describe something that's related with computers, and secondly, interacting with the channel that the message should be sent to should be a better way than to use about 7 elif checks. That's just not very pythonic.
snipe msgs
not really
what's that?
never heard of such a term as "snipe" when it comes to past messages
Verification feature
idc not gonna remake this
dude relax, they most likely made a mistake, no need to get so heated
even after an edit it logs it to
@wispy spade will discord.Message work?
well you'd have to define message to be able to use it like that
afk_check_messages = ['Afk check', 'afk check', 'AFK CHECK']
@client.event
async def on_message(message):
for i in afk_check_messages:
if i in message.content:
print(f'[{get_time()}] -> Prevented AFK check from: {message.author}!')
await message.channel.send(random.choice(sentences))
else:
pass
``` when someone does say something in `afk_check_messages` it sends it 3 times
With the rise of NFTs there are many self bots now
the only way you learn from something is to make it better, why don't you want to make what you already have made better?
you can get the message from ctx too
but it has to be for moderation as you cant log a msg for no reason since its against tos
hmm okay
but what would qualify as a message worthy of logging?
allot
no I mean I literally asked him with many different ways it would be possible and he kept getting annoyed and saying its literally not possible
he was owner of discord interactions discord
everything as your logging them for moderation
and thats the reason
me who tried something like that and failed
then now you know it is, and now you have to figure out how to use that knowledge to make it work!
Break the for loop after sending the message
not making this to learn
so any reason as long as it's under the purpose of moderation?
@slate swan
File "C:\Users\W 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'member_descriptor' object has no attribute 'split' ```
I just realized levi
more errorrs
okay, reasonable. If it works, and if the objective allows for such an unpythonic way, that's fine if it works, but i don't suggest that.
youll need a reason to log them which in this case its moderation
@slate swan i dont think i can make a economy bot.😅
yeah, do you have any other suggestions?
! resources dude just go through this
it's mainly just using databases.
i tried making a comand just for beg
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yeah levi crackerman
make a auto mute on a msg burst
sql has no attribute to load so what do i do?
what's the code now?
how do i do that
write break in the line after the ctx.send
tried that before, was a pain. I want something that's more related to databases, which in this case might be an economy system, where a user can buy certain colors for their roles?
anyone has repos i can contribute to im kinda bored
would you want to help me make a discord api wrapper?
I have some game suggestions
have repos*
should make a shop of some sort
sure
yeah i was thinking about that
dm lol
alright, do you want to vc and work on it?
a marketplace
i cant really rn because i need to finish my projects but in down later
yeah maybe where the amount of messages you send in the server, the more 'currency' you get, and you can buy color roles or certain features?
sure, add me?
alr
yeah
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "type") to str
Dude
message = discord.Message
@bot.command(name="repeat")
async def repeat(ctx: commands.Context):
await ctx.send("You sent:" + message)```
oh yeah
You are defining message before the command
that's a good suggestion
and you can't concatenate (or add) it to a string
you defined it before you referenced it in the command
so how do i make it send the message
again, you are probably looking for ctx.message or something
i think
reason = [""]
while len(str(reason)) < 1:
if reason.emoji == "9️⃣":
break
if reaction.emoji == "0️⃣":
reason.append("Other")
if reaction.emoji == "1️⃣":
reason.append("Too short application \ poorly explained")
if reaction.emoji == "2️⃣":
reason.append("Lack of hours on Unturned \ inexperienced")
if reaction.emoji == "3️⃣":
reason.append("Bad english \ grammar")
if reaction.emoji == "4️⃣":
reason.append("Inactivity \ Lack of hours on ICE RP")
if reaction.emoji == "5️⃣":
reason.append("Too many incorrect answers")
if reaction.emoji == "6️⃣":
reason.append("Lack of developer skills")
if reaction.emoji == "7️⃣":
reason.append("Cannot be trusted \ too many bans")
if reaction.emoji == "8️⃣":
reason.append("Troll application")
embed.add_field(name="Reason for denial", value=str(reason), inline=True)
await chl2.send(embed=embed)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required
just say if there is smthing wrong dont comment on the reaction or button shit
please
im getting cancer from this shit fr
i tried it and it sent this:
that's just how the message instance gets represented
you want to access the content
yes
Can it be because you named your embed "embed"?
how do you make your bot copy an emoji and put it on your server. Example
I write: !emoji 
The Bot copies that emoji and makes it a server emoji
Please help me out thank you!
anyone know fix?
anyone
just to clarify the bot copies the emoji and adds it the servers emoji list that the command is in
Try changing the name of your embed
that wont matter
One of the fields in the embed has a value that's empty
its cuz one of the fields is invalid
So check the str(reason) thingie
it should be a datetime obj
timestamp=datetime.datetime.utcnow()
so it shouldn't continue before its valid
howi used ctx.message and got this
well check what str(reason) does cause it might very well be empty
can you help me?
Is it because of the emojis
again, you're looking for the content of the message, not the message itself
doesn't work
what did you try to do?
then how do i get it??? please tell me
why might this not work ?
while len(str(reason)) < 1:
Nvm I am dunb
alr ill lyk how it goes!
@bot.command(name="repeat")
async def repeat(ctx: commands.Context):
await ctx.send(ctx.message)
Assuming the current reason [""], the len(str(reason)) < 1 will not run.
just ctx
Since the str of [""] is [""] which is 4 chars, not less than 1
well how do I check if reason is empty
just do len(reason) instead of converting reason
what did i do wrong?
and you also would want to remove the "" that's already in there
doesn't work
Didn't close the bracket
forgot to close parenthesis in both embed variables
@slate swan help mee
use a kwarg
while len(reason)!=0:
so ctx(*) ?
huh
doesn't work dude
coinflip command works thanks guys :D<3
how does it "not work"?
no
it just doesn't work
@soft narwhal
@bot.command()
async def repeat(ctx,*,say):
await ctx.send(say)
wtf is wrong with this shit
it just skips
the while loop
like it never was there
well it shouldn't cause not [] would be True
when an item is there it should become False
are you still receiving the same error from here?
yes
and the error is cuz reason is invalid
and reason shouldn't be invalid
if it went thru while
while reason:
doesn't work either
Same error?
bro
If you are using a list, did you change the str(reason)
read the code dude
is this list still empty?
yes
are there any other fields apart from that one?
shouldn't matter
the list is empty
but here
embed = discord.Embed(title="Application denied", color=0xFF0000)
embed.add_field(name="Applicant", value=reaction.message.content, inline=False)
embed.add_field(name="Denied by", value=user, inline=False)```
Are you sure the while loop is not running
if reaction.emoji == "9️⃣":
break
if reaction.emoji == "0️⃣":
reason.append("Other")
if reaction.emoji == "1️⃣":
reason.append("Too short application \ poorly explained")
if reaction.emoji == "2️⃣":
reason.append("Lack of hours on Unturned \ inexperienced")
if reaction.emoji == "3️⃣":
reason.append("Bad english \ grammar")
if reaction.emoji == "4️⃣":
reason.append("Inactivity \ Lack of hours on ICE RP")
if reaction.emoji == "5️⃣":
reason.append("Too many incorrect answers")
if reaction.emoji == "6️⃣":
reason.append("Lack of developer skills")
if reaction.emoji == "7️⃣":
reason.append("Cannot be trusted \ too many bans")
if reaction.emoji == "8️⃣":
reason.append("Troll application")```
this is the while loop
nvm the error was from something else but the loop still is not running
what are some ways to make a embed look fancier?
can you throw a print in the loop and see if it's actually running or not?
if the reaction is 9️⃣, then i'd just break and not add it to the list
so that could be a reason
9 is supposed to break it
@bot.command(aliases=["aliases go here"])
async def command():
pass
I assumed you were referring to command aliases.
also I tried, it doesn't run the loop
is reason empty?
what's reason?
i know it's a list but what are the contents?
if it's not running it likely means there's something in the list already
(assuming there's no other ifs or conditions that could cause it not to run)
What's the while statement
...
does anyone know the reference I can use to find the name of the server the bot is in?
@thin kelp
so it's now while reason?
Is there a way I can restart my bot etc from discord
yes.
Lol 😂 how would I go about doing that
So, my bot just stopped, i tried to purge the entire channel using a command -
Bruv
do while not reason:
i tried to do py await ctx.channel.purge(limit=9999999999999) but it had the same result
i have one of those, i wanted to purge the WHOLE channel
And just run the number up to some outrageous number
:/
That’s what I do
alr
There is
how
See
ok no wonder why it isn't running
since reason is []
Clone the channel and delete the old copy with all the messages in it
instead of fetching all the messages and deleting them
just keep it as while not reason: and that should work
how would you do that with a bot?
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to do this.
New in version 1.1.
channel.clone()```
!normally just do ! Clear then 10000000000000000
oh you CAN do that, huh
Yeah, clone it so all the perms copy over
And that clears the thing but what ever the clone thing will work
I mean it would probably be faster and less work intensive for your bot as well.
Clone channel then delete the old one.
alr
english please, @spark sleet
hey mina long time no see
👋 hi
how r u
pretty good :) you?
thats good to hear,im good
welp i gtg do 205 more functions had a great talk with you
haha gl!
thank you
Wait I keep seeing you say you have to do 300 functions, but why?
project im doing lol
for channel_id in channel_list:
channel = bot.get_channel(int(channel_id))
embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
await asyncio.sleep(3)
await channel.send(embed=embed)
doesn't work
channel = bot.get_channel(int(channel_id))
doesn't apprenlty get the channel rly
the channel object

bro
anime rly
your enemy
is here @slate swan
What's the practical difference between message and ctx?
Context and message. Context has a lot of info about the bot, guilds, users and the current message, channel, member as for message being only info about the message itself.
Got you 🙂 I will have to look at the docs later to understand better but appreciate that overview!
Context shares info with message
Context is just message with a chance of being valid, that is valid meaning there is a command behind it
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
I'll invoke your parents if u dont help me with this
Ok
I don't like spammy scripts :(
it needs to send it on every channel that I have listed
any1 know how to make a channel what says Bot Online when it comes on and when its gone off it says bot offline?
Have it send a message to a channel?
not made for spam
just help me aight?
cmon
if i get roles like this, do i need to do role = await ctx.guild.get_role(role_id)?
no, only use await when using fetch_role
anyone know why??
alr
You can't tell when the bot goes offline unless you use another bot
does it return None?
Remove the brackets
thanks
is it possible to fetch a single role, bc i can only get_role not fetch_role using ctx.guild
iirc you have to use bot.fetch_role() when fetching a role
Does commands.HelpCommand not pass client the same way commands.Cog does?
How do I keep my bot online everytime?
?? You should be able to do both
i have this:
unranked = bot.get_channel(760103928393629716)
await unranked.send(embed=emb)
i get this error:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 299, in uhc
await unranked.send(embed=emb)
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/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 'send'
get_role and fetch_role do the same thing, get_* functions return it form the cache, while fetch_* functions do an API call, hence the coro
!.join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
How do I get ctx from a get_destination messageable in my help function?
i can't do py await client.fetch_role(role_id) await ctx.guild.fetch_role(role_id) either
so, you need context for a message?
nvmjust made it better
What do you mean you "can't" do it
it doesn't exist
Self host or pay for a VPS
for me, client.fetch_role and ctx.guild.fetch_role don't exist
Yeah oddly discord only lets you request ALL roles
(shudders) self host...
you can fetch_roles
then just loop through the list and get the role i want?
I mean micro computers fall under self host
alr
Self hosting with, say, a raspberry pi isn't all that bad
get_role() gets the role from cache, right?
aw, i hope discord updates support for role fetching and disnake adds it
Though of course it's not very powerful nor scalable and you'll have issues once your bot gets bigger but yes
Yeah I always found that kind of stupid
I suppose it's quite easy to fetch a single role though, just combine fetch_roles() with utils.get
The electrical consumption of a raspberry pi is minimal
so, from discord.utils import get role = get(role_id, await ctx.guild.fetch_roles)?
or not, is there a diff way to use utils.get bc i've never used it before
do you have to await discord.utils.get or not?
Hi why i get this error
Code
@commands.command(pass_context=True)
async def color(self, ctx):
await ctx.send("#{:06x}".format(random.randint(0, 0xFFFFFF)))
error
the command is working but i still get this error
lets say i wanted to make a python discord bot, but i wanted to be able to change settings through a website, how would i make that?
or does someone have a git source for something like that
or a video tut
can someone please send me an example command using buttons for discord.py
I have never used them before but want to start now
i personally have used a setup as follows:
- my bot grabs a guild's configuration from my database (when needed) and caches it for a certain period of time
- web server sends a message to the process running the bot that a value was changed
- the bot refreshes its guid configuration cache for that specific guild
what are you trying to do?
thats a hex code
generate a random hex code
and i used redis pub/sub for sending the message from the server to the bot
and its working but i get this error
ah alright thank you, is there some sort of documentation or video you would reccomend to look into first?
did you code that or find that online
are you using python?
yea
import random
print "#{:06x}".format(random.randint(0, 0xFFFFFF))
``` i found that online
and i make a command with that
i mean well it's quite simple. you can set up a redis server on your machine and go from there
there are many many redis libraries, even for python. a simple google search would lead you to those options.
well
ok its possible to send a photo with the color?
i wish i didn't have to turn you away to google but i programmed my bot and server in javascript
not sure how much that would help
meaning....
i'm happy to send code snippets however, if that will help you (again, it's in javascript)
use a hex color api
where can i find that?
This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.
This video might also apply to other...
i appreciate that
i just ran this in a repl and i'm not getting any error
Oh you wanted an example
Sorry then
But I think this should help too
yeah no worries
is pycord better or worse then discord in your opinion
isnt pycord simply a wrapper?
Pycord is just a fork for discord.py
so did they edit anything massive?
Not really
to where my discord.py code would be massively effected?
I think you can use 99% of discord.py Code with pycord
tf
i see
first off repl isnt the way to go xD use VSC if possible
>>> '#{:06x}'.format(random.randint(0, 0xFFFFFF))
'#ef7098'
repl isnt great for hosting bots unless its only used to test
the python repl
?
Read pinned messages
There is a message with reasons Why repl isnt Good for hosting
jesus yall
Ok
you don't have a clue what i'm talking about
what?
Yes
i think we have a very big clue
? just cause you come from discord.py and people have told you to stay away from repl.it doesn't mean you know what i'm talking about
what are you on about
REPL stands for Read Evaluate Print Loop, and is the name given to the interactive MicroPython prompt that is accessible on the Pycom devices. Using the REPL is by far the easiest way to test out Python code and run commands. You can use the REPL in addition to writing scripts in main.py .
that what youre talking ab??
take a guess
its possible after the hex color is generated to send a picture with the generated hex color?
@commands.command(pass_context=True)
async def color(self, ctx):
await ctx.send("#{:06x}".format(random.randint(0, 0xFFFFFF)))
``` code
try using pillow
pillow?
haven't used it personally so ask around for help
ah that
heard it's a royal pain in the ass to download
any1 know how to fix SyntaxError: 'await' outside function
hey guys
Is there a good way to iterate through the keys and subsequently values in a list of dicts?
I will post this in general actually since it's not discord related
You can flatten the list into just a list of the dict's values
You have the dict.values() method, and you have the dicts
So you can just do a list comp, E.g [dict.values() for dict in list_of_dicts]
Then you would iterate the newly created list
oh wait I read you wrong, you want the keys and the values
Thought you only said values
any ideas?
i am trying use cogs, and its like thispy class Example... async def ex1(): ... @commands.command() async def ping(): await ex1() and i got error ex1 is not defined why?
SyntaxError: 'await' outside function for i in await ctx.guild.invites():
You must access ex1 through the instance of your Cog, likewise this means all your methods need to have the first argument self which is the instance
Cogs are classes, thus follow the same rules as classes
Unless the method is a staticmethod or a classmethod
await can only be used inside an async function
hey guys im trying to host my discord bot. my bot uses json and os. do i need to state this in the requirements?
no, those are builtins
only stuff that you intalled via a package manager like pip should be added to the dependencies
ah i see
if you can, you should try to find a way to have your package manager automatically add the dependency for you
Poetry is very good for stuff like that
@pliant gulch should functions also have self as first arg?
thanks :))
If the functions are within the classes indentation level yes
if they're a regular method, yes
any1 know how to fix
File "C:\Users\liamd\Documents\MainGen\MainGen\main.py", line 355
totalInvites = 0
^
IndentationError: expected an indented block after function definition on line 354
*you're
in your status
so you're the clown
!tag indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
i forgot. how do i make a on_member_join? im like really confused
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Does anyone know how can I hide error discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction from console?
Ignoring exception in on_member_join Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 16, in on_member_join embed.set_thumbnail('https://cdn.discordapp.com/avatars/836727600067117096/e597053a98959e69d77cc5d1762f56e4.webp?size=4096') TypeError: set_thumbnail() takes 1 positional argument but 2 were given
set_thumbnail takes a url kwarg in which you didn’t pass
embed.set_thumbnail(url="your link")
@blazing lynx
I'm a little bit confused, for some reason this command works fine when receiving an integer as input but when inputting something like letters it does nothing rather than getting a ValueError as expected:
@commands.command(name='turn_time', aliases=['turntime', 'time', 'turn'], help='sets server turn time')
async def turn_time(self, ctx, turn_time=40):
try:
time_per_turn = int(turn_time)
hey @patent lark how can i display the members name that joined inside the embed that it sends?
thanks!
I have a try except else for the method but it only ever hits the elf, when it receives a bad input it doesn't even enter the try block
You can use function annotations to have arguments automatically converted to different types
I suggest you use that instead of manually converting, especially for trivial types like ints which are supported out of the box
turn_time: int = 40
I was using the type casting so that it would trip a value error if a bad type was input eg string
and then I could handle the value error and send a message in response
Discord.py will raise conversion errors and you can register an error handler if you want to output the error in a different way
Could you give an example of a simple method and error handling for bad conversion?
Is there any way to pass the args into the error?
My old error handler had the args they put in the message
so here is what I have at present
@commands.command(name='turn_time', aliases=['turntime', 'time', 'turn'], help='sets server turn time')
async def turn_time(self, ctx, turn_time: int = 40):
try:
curr_server = await self.get_local_server_object(ctx)
channel_to_be_sent = ctx.channel
time_per_turn = int(turn_time)
if time_per_turn < 10:
print('less tahn 10')
message_to_be_sent = '**Turn Time too low! 10 seconds is the minimum value.**'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
elif time_per_turn > 120:
print('greater than 120')
message_to_be_sent = '**Turn time too high! 120 (2 minutes) is the maximum value.**'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
elif time_per_turn < curr_server.word_count:
print('time per turn too low')
message_to_be_sent = '**Turn time too low! Maximum word rate cannot exceed 1 per second.**'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
else:
print('normal')
curr_server.turn_time = time_per_turn
message_to_be_sent = f'Successfully changed server turn time to **{time_per_turn}**'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
@turn_time.error
async def turn_time_error(self, ctx, error):
channel_to_be_sent = ctx.channel
if isinstance(error, commands.ConversionError):
message_to_be_sent = f'**{turn_time}** is not a valid input - please enter a valid integer'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
but {turn_time} would not be a resolved reference since turn_time_error has no access to it
I believe the default message generated by the exception already includes the original input
But you could get it from ctx.args or ctx.kwargs if you really wanted to customise it
I suggest you just try to use str(error) as the message because chances are you'll find it sufficient
Cool, it is working now but the ctx.args didn't work as expected
if isinstance(error, commands.BadArgument):
message_to_be_sent = f'**{ctx.args}** is not a valid input - please enter a valid integer'
await self.message_sender(channel_to_be_sent, message_to_be_sent, 1)
returned
[<cogs.barbot.BarBot object at 0x000001B4727DE470>, <discord.ext.commands.context.Context object at 0x000001B4729778E0>] is not a valid input - please enter a valid integer
so obviously it is returning a list with two objects
I don't think it will work anyway cause it can't populate the args list due to converter failing
Maybe ctx.kwargs then? But another way you could do it is; Just raise a custom error which extends Exception to take in your argument turn_time
Where would I go about trying that Andy?
My old method was using an Exception converting the type of the string input
You would start off by making a new class which inherits Exception, change the __init__ method to take another arg that being your turn_time. Then construct the super class, set the arg then raise it
You might not need to construct the super class but I would do so anyways
Then just isinstance to check if this error captured is your custom error, if it is access the custom attribute
I disagree. If you really are unsatisified with the default message in BadArgument, then either
- Accept the arg as a string and manually convert and handle the error within your command, as you were originally doing
- Define a custom converter that will raise a custom exception which has the argument name as an attribute. This will give you a generic way to handle the error I suppose.
I will give it a try, I will be testing things out throughout the night, is there any way to have a cog wide error Handler like how you can do Cog check to check 4 permissions?
The default message is "Converting to int failed for parameter turn_time".
Yeah, that is a little robotic as a response, my target audience is not exactly technical so it would be better to have something that avoid possible confusion so custom handling would be preferred
There is cog_command_error for cog-local errors and on_command_error for global errors
Don't they want to get the value of the argument passed though? Thus the default would be not ideal unless I'm confusing what they wanted
Not sure. I thought they wanted the argument name
@slate swan im done wih the 1k functions project happy,ill push it to pypi later or tomorrow 🙄
No, I want the argument that they entered itself
Ok yea so the value
How would I access that from the given ctx? I think there was something like ctx.message iirc so I will test that
That is true you could do that
You need to make sure you trim off the prefix and the command name itself
But then you manually have to parse the message and it isn't necessarily trivial
Unfortunately discord.py doesn't have the provisions for what you're trying to do. You'd either have to just do it the manual way, which works but is not very "scalable" (imagine doing that for 5 arguments, or for 20 commands), or you'd have to write a significant amount of custom code to get a better converter and error handling system
Just make a custom error like I mentioned earlier then, it's scalable
But how would you get ALL converters to raise that error?
You'd have to make a custom converter like you said to raise the error
You could also just manually raise it
But then you need a custom converter for every type you need
Good point. Unfortunately it still makes you work for it.
Just a poor design choice with discord.py
The sad thing is that it would've been trivial to include the parameter name and value as attributes on the exception
BadArgument has no reason not to have properties for the argument raised
That's absurd haha, yeah, the ctx.message from the error doesn't have the actual message
I figured it out anyway though 🙂
Getting this error and I have no idea why
Traceback (most recent call last):
File "c:\Users\MyName\Desktop\dubsbot\Discordbot.py", line 62, in <module>
bot.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\MyName\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 730, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.adminlogs' could not be loaded.
I deleted adminlogs from my files since it was no longer necessary and even removed any mention to it. Why is it still being called and why is there an error?
Figured out the issue. I was going to the wrong path. ;D
can you print the tree of your project folder?
I'd also like to see the relevant code, so the for loop
#Location of the COG files.
for filename in os.listdir('c:/Users/MyName/Desktop/dubsbot/cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@potent spear
I got an issue now that when I sent the code to my friend it doesnt work ;-;
ofc it doesn't work, your friend's filepath is different than yours
can you print this for me in the file pls
from pathlib import Path
print(Path(__file__))```
^
give me a break ive programming for 7 hours straight smh ill do it tomorrow 
@slate swan you finally created a repo?
nah not yet
but ill do it tomorrow
im going to publish it to pypi and github tomorrow
want to know what it does cause i can say
How can I incorporate asyncio into my bot so that when it makes requests it can respond to other commands before the request has finished?
your bot isnt asynchronous? 
the commands look like
@bot.command()
async def request():
make_request_to_website()
but when it does that it can't also respond to the ping command
until it's finished with its request
I think if you use aiohttp it won’t happen
if you're using requests library or something , use aiohttp instead
yea
I'm not, it's actually using the openai library
since it's using that library it has to process whatever data is sent before it can be returned and while it's waiting for a response nothing else can be run
what does it do?
The user runs a command, whatever they enter into that command gets sent to openai and processed by their engines, and then the response is sent to the user. https://github.com/DH711-creator/ai-discord-bot if it's helpful
whatever lib you're using must be blocking, thats why the bot stops until it has finished a pending command.
for asyncio which is the concept around discord.py and other forks, you need to use something that is not blocking. i suggest learning aiohttp
so then the command works simultaneously
across all the servers that have your bot
use the async version of the library
if there's none , use run_in_exexcutor
im not sure but this might be related https://github.com/coreylynch/async-rl
I'll check that out, thanks!
You could also just run in executor if that doesn't work
how would I do that?
great great, thank you too
would either of these solutions be preferrable over the other for any reason?
if the library works , its preferable
else run_in_executor exists
Oh kek didn't realize you said run_in_executor alr
oh I thought those were different somehow
Hey, it's very late and Im just very confused why Im getting this problem. I just copy/paste a code from another bot I have to another one, I dont see any reason why it shouldnt work and something weird is that the import discord is like greyed like Im not using anything from that package and Im getting an error saying this AttributeError: module 'discord.ext.commands.bot' has no attribute 'event'. I have probably just missed something small but I really cant think of anything rn
you defined bot as commands.bot , which should be commands.Bot
discord.ext.commands.bot -> discord.ext.commands.Bot
@surreal sierra
yea........... thx, really dumb of me but thanks XD
you're not the only one
me rn: 🧍♂️
Is there a way I can execute some code before the bot goes to fulfil the command?
(For more context, I want to make a blacklist command, and I want the bot to check if the author is blacklisted before it executes the command)
uh
well i wrote a really long paragraph before but idk how helpful this will be to you
---> Adding a check so only one person can run a command
This can be done in many ways
1) an if statement inside the functionpy @bot.command() async def command(ctx): if ctx.author.id != user_id: return
2) a dedicated check
@bot.check
async def user_check(ctx):
if ctx.author.id != user_id: return False
return True```
**3)** a non-specific `check`
```py
@bot.command(hidden=True)
async def command(ctx):
"""whateve you want"""
@bot.check
async def user_check(ctx):
if ctx.author.id != user_id and ctx.command.hidden: return False
return True```
**4)** `owner` only, if this suits you
```py
bot = commands.Bot(owner_ids=[...], ...)
@bot.command()
@commands.is_owner()
async def command(ctx):
"""whatever you want"""```
!d discord.ext.commands.check || you're looking for a check
@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").
so like method 2 but py if ctx.author.id in blacklisted_list: return False return True
i have a bunch of material that ive written just lying around
awesome
but what does hidden=True do btw?
means a command is hidden and most automatic help commands wont show them
🙇
im proud of this ngl
.bm
nice
Is helpful
cheers :D
.bm
wanna see some other crap?
someone should pin this tbh
no
Yessir
Why not
Pin ig
---> Sending a quote on a timer
you're going to want to have 3 things:
a) a list of channel ids
b) a database to store the channel ids - it can just be a json file, but you probably want the bot to remember to send the quotes, even if you restart the bot.
c) a discord.ext.tasks.loop.
In this example I am going to show how you may want to do it, but I will not show it linked to a database. You can do that part yourself. My github project where I have done this is https://github.com/caedenph/jesterbot.
@tasks.loop()
async def quote():
### Get channel_ids from database here ###
for chan_id in channel_ids:
channel = bot.get_channel(chan_id)
await channel.send(quote)
in this example there is channel_ids, which holds the channel ids, and tasks.loop which is discord.ext.tasks.loop
You can also link this to a command,
@bot.command()
async def setup_quote():
#apend to database```
no like a channel pin
idk if this ones real helpful
---> Kick command
@bot.command()
async def kick(ctx, member:discord.Member):
await member.kick(reason='get kicked')
await ctx.send(f'{member} got kicked')
: ctx is a default argument. ctx -> discord.Context. ctx.send sends it to the channel it was invoked in.
: member is a member, like @manic wing . This is an instance of discord.Member. You can get information from discord.Member like .name, .discriminator (the numbers after the #), .created_at (when you created the account)
: by TypeHinting member to discord.Member, it means you can do stuff like ?kick @Caeden#7205
bruh.
hm?
You should make a GitHub repo with all these things lmao
should add a optional reason
i agree
Whyyy
i have a budget of only one python repo :(
true should do that
why not?
Because you always want to kick a member when u use the command
.bm
i ment the audit log reason
else , just deal with the error with a handler
Oh , as the reason?
ic
no a arg for the reason kwarg?
and should add a check
await member.kick(reason=kwarg)
what i ment
understandable
yup
My commands are working slow. I tried to comment half of the imports and it works faster. Is there any way to make the command called by the user automatically import it's required import without importing everything at once even if it doesn't need it?
I am trying to upload my bot to a hosting service.
The module is found in:
.local/lib/python3.8/site-packages/discord/
Do I need to change the 'import' in my code?
go to startup -> additional python packages -> write discord
I have multiple commands in 1 cog btw (like all moderation commands in a cog called "moderation" and all that)
or discord.py actually
I'll try regular discord
any help?
to make the command call it's required import
most people don't even read audit logs anyway
instead of importing everything at once
you should try importing only the stuff you need , like instead of ```py
import discord
bot = discord.ext.commands.Bot(....just import the Botpy
from discord.ext.commands import Bot```
it saves resources
I use it to keep track of why a person was kicked/banned in case they make an alt.
will this even work?
and?
are you sure the discord folder has imported the ext folder?
didnt work 😦
this makes very slight changes in terms of the speed of your code operation?
@bot.command(aliases = ['cooldown'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def cd(ctx):
names = ['hunt', 'mine', 'boss','daily']
res = ''
for name in names:
name = bot.get_command(name)
seccd = round(name.get_cooldown_retry_after(ctx))
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = seccd % 60
mincd = (seccd - rseccd) / 60
elif mincd > 59:
rmincd = mincd % 60
hrcd = (mincd - rmincd) / 60
if rseccd == 0 and rmincd == 0 and hrcd == 0:
res += f':white_check_mark: {name}\n'
else:
res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
embed = discord.Embed(
description= res,
color = discord.Color.blue())
embed.set_author(name= f"{ctx.author.display_name}'s cooldown",
icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
the logic isnt working ;-;
the operator part
i dont get the cooldown. once every 1 second lol
why would you show a command that can be easily made better as an example
...
works like a charm
u wont wan pepo to spam rpm cd to break ur bot
show what u did
as they said , commenting out some stuff makes it faster , im just asking to import only the stuff they need , the Bot import was just an example
that wasnt what you did at all https://github.com/Rapptz/discord.py/blob/master/discord/__init__.py
names = ['hunt', 'mine', 'boss','daily']
res = ''
for name in names:
name = bot.get_command(name)
seccd = round(name.get_cooldown_retry_after(ctx))
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = seccd % 60
mincd = (seccd - rseccd) / 60
elif mincd > 59:
rmincd = mincd % 60
hrcd = (mincd - rmincd) / 60
if rseccd == 0 and rmincd == 0 and hrcd == 0:
res += f':white_check_mark: {name}\n'
else:
res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
help ;-;
Requirements file```txt
discord.py==1.7.3
requests==2.25.1
validators==0.18.2
discord==1.7.3
Import list on bot.py```python
import discord, asyncio, os
from discord.ext import commands
import discord.utils
@slate swan
seccd is in seconds
but some cd has 10k+ sec so im trying to change it to mins and hr
im confused? how would blocking out imports make a huge difference in the speed?
dont ping people
change python version to 3.8 ( docker image)
maybe youre using stuff thats blocking
dont fill the REQUIREMENTS FILE
no not that. I mean how can I make my functions call it's required import instead of importing everything from top
coz I;ve already installed them and I dont want the startup to keep running it and taking forever
:/
WOO!! \o/
import it inside the function
Ty sarthak. I'd kiss you but my doctor says it's a bad idea.
unused imports have a trivial impact on the compiler, but there are no imports in the byte code or at runtime. unused objects can be optimised.
i was hoping someone can help my with a blackjack command for my bot. I am trying to add buttons and make them work forever like so:
@bot.command():
async def blackjack(ctx):
msg = await ctx.send("Hit or Stand")
#Adds buttons
#checks which button is pressed
if button_pressed = "Hit":
#Do math then continue with the code if its not over 21
else:
#i can code the outcome stuff ofc
All i need help with is the button setup please help me out thanks!
What?
that using dsicord.py and not pycord
whats button_pressed
just a placement i put
yeah , that wont be a big difference
to show what im trying to get
no
i have no clue how to use buttons
^
he doesnt have it anywhere in his code
thats the wrong code
thats why i asked
#Adds buttons
its just a place holder to show
LOL
wdym , ext is a folder inside the discord package , why would that cause an issue
bro i have been trying at this button bs for forever LOL
the pycord discord is made with a bunch wannabes and are stupid
they shouldnt even be verified discord
seccd = round(name.get_cooldown_retry_after(ctx))
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = seccd % 60
mincd = (seccd - rseccd) / 60
elif mincd > 59:
rmincd = mincd % 60
hrcd = (mincd - rmincd) / 60
if rseccd == 0 and rmincd == 0 and hrcd == 0:
res += f':white_check_mark: {name}\n'
else:
res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
```help me
whats wrong here
its not an error
just my brain logic having error
oof
why is everyone gone within a sec
=.=
Im reading your code
oo ok
you dont have a seccd <59 and set your first if to >= 59
What happens if seccd is <59?
have some respect for people, heres a button example since you dont know anything about buttons https://github.com/Rapptz/discord.py/blob/master/examples/views/ephemeral.py
i got cursed out for joining and pinging someone for help
and thank you
you arent supposed to ping people for help though
so because someone didn’t enjoy being pinged means they are stupid wannabes?
logic doesn’t make sense, but okay.
lmao
:/