#discord-bots
1 messages · Page 753 of 1
yeah I figured that but how to calculate if the situation is compounded half yearly/quaterly
NVM!
for quarters, u multiply the time by 4 and divide the rate by 4. same for half yearly, just divide and multiply with 2
Hello I am trying to pass a kick command, sadly my error handler does not help, does anyone know the solution?
from discord.ext import commands
import os
import discord
import time
from datetime import datetime
import random
class Moderation(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_mng = None
@commands.command(name="kick")
@commands.has_guild_permissions(kick_members=True)
async def kick(ctx, member : discord.Member, *, reason = None):
await member.kick(reason=reason)
def setup(bot: commands.Bot):
bot.add_cog(Moderation(bot))```
Can you write the code and send if that's not too much to ask
i do not know, sry.
gotcha thanks!
I am very sorry your code isn’t working. Unfortunately, you aren’t good enough at coding to debug this. I think you should try something else like teaching or Among Us.
Uhhhhh?
is the cog being loaded?
🤣
Okay...
i believe this problem is a skill issue.
show yr error handler
from discord.ext import commands # Again, we need this imported
import os
import discord
import time
from datetime import datetime
class ErrorHandler(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_mng = None
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error:commands.CommandError):
"""A global error handler cog."""
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.CommandOnCooldown):
message = f"This command is on cooldown. Please try again after {round(error.retry_after, 1)} seconds."
elif isinstance(error, commands.MissingPermissions):
message = "You are missing the required permissions to run this command!"
elif isinstance(error, commands.UserInputError):
message = "Something about your input was wrong, please check your input and try again!"
else:
message = "Oh no! Something went wrong while running the command!"
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
def setup(bot: commands.Bot):
bot.add_cog(ErrorHandler(bot))```
ah I got the issue
in the else statement, add another line raise error
at the end ^^^
alright it gives me this
ohh yeah im sorry i forgot
so its taking ctx as self and member as ctx
mhm
!d discord.Embed.colour
The colour code of the embed. Aliased to color as well. This can be set during initialisation.
smh Python
e = discord.Embed(colour=discord.Colour.green())
Best lingo there is
???
@native wedge
You can change green to whatever color
how do I delete a message after a timeout in nextcord
await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when a view’s timeout elapses without being explicitly stopped.
Lmao
we dnt talk about that :c
I don't think so
Lmao idk
pp

can we stop the emoji spam
yes
yea it is
Thanks
okei...
My vsc isnt working well
:c
I like the app but I cnt code on it

So if it doesn't have a license everyone can copy
Nope
Why?
That's called a no license
That does not mean it's free to take
In the case of a no license it is not permissive at all
Thus you cannot copy, redistribute, etc
How work?
Time to make all my repos non licensed then
You’re under no obligation to choose a license and it’s your right not to include one with your code or project. But please note that opting out of open source licenses doesn’t mean you’re opting out of copyright law.
license up my boys
Thought non licensed meant anyone can copy
erm..
that actually means
everyone can copy your code
also you need to include the MIT license file into the projects root folder
there's no such thing
if you don't want people copying your code you make it closed-source
Most if not all of the licenses provided on GitHub allow people to use it for their own private use
mee6 isn't open source though..
Most of those big bots aren’t open source
No license
Not as in no license at all exists, "no license"
Or any license that has terms of no copying
MIT is permissive so def not something you want if you don't want copiers!
Without the owners consent

the later
Called "no license" and you don't give a license either
People call it no license
No just don't have a license
I mean, but it's also good to specify you are doing No license
Otherwise people will think it's an oversight
^
Transparency
that has nothing to do with licenses
I'd much rather have microsofts source code and not be able to copy anything
If I was able to see all the telemetry stuff they do!
well most certainly that is a very specific case
Not really
my guy isn't about to create windows 12
Can you 100% trust any company without seeing the internals?
💀
hellow. ihave this code. ```python
@nextcord.ui.button(label=f"✅", style=nextcord.ButtonStyle.gray)
async def Question1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
test = 0
test += 1
user = interaction.user
emb=nextcord.Embed(title="✅ Approved Suggestion", description=f"Ευχαριστούμε για την γνώμη σου!{test}", color=0x00FF00, timestamp=datetime.now())
emb.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb, ephemeral=True)
but it doenst update tha test and it keeps saying 1 no matter how many times i press the button
could put it in the readme file
could put it in the description
in the code with __license__
Just somewhere in the codebase announce that the project is no license
You don't need license at all
why? If the project is not open source and only for you
But you have no license
you don’t need a license unless you need to have the rights to it and specify what people can do with it
No, just don't use __license__
if the code is currently only you using it and it’s not public, a license won’t help anything
You'd use __license__ metadata header if you HAD a license
but you are doing NO license
Just announce somewhere in the code base you are going No license so people know it isn't an oversight
IE. read me
sorry for interrupting you but could you help?
you choose ¯_(ツ)_/¯
so that people don't think of u as a beginner because of not having a license
🚪👈
??
cz everytime a button is clicked, u r setting test to 0 and then adding 1
think about it yourself... first 0, then 1, then 0

i made it like that```python
test = 0
class sugbut(nextcord.ui.View):
def init(self):
super().init()
self.view = None
@nextcord.ui.button(label=f"✅", style=nextcord.ButtonStyle.gray)
async def Question1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
test += 1
user = interaction.user
emb=nextcord.Embed(title="✅ Approved Suggestion", description=f"Ευχαριστούμε για την γνώμη σου!\n Total Votes: {test}", color=0x00FF00, timestamp=datetime.now())
emb.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb, ephemeral=True)
but it gibes this error
yea
u can instead make a class variable in the init
😔
nou
i cnt even finish my discord bot 

what
:))
now with this, gives this erroe ```python
class sugbut(nextcord.ui.View):
def init(self):
super().init()
self.view = None
self.test = 0
@nextcord.ui.button(label=f"✅", style=nextcord.ButtonStyle.gray)
async def Question1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self.test += 1
user = interaction.user
emb=nextcord.Embed(title="✅ Approved Suggestion", description=f"Ευχαριστούμε για την γνώμη σου!\n Total Votes: {test}", color=0x00FF00, timestamp=datetime.now())
emb.set_author(name=user.name, icon_url=user.avatar.url)
await interaction.response.send_message(embed=emb, ephemeral=True)
`NameError: name 'test' is not defined`

total votes: self.test lol
u still have it named as test
thanks guys xD
what
Idk
😭
Lol
@commands.Cog.listener()
async def on_message(self, message):
messageAuthor = message.author
if bannedWords != None and (isinstance(message.channel, discord.channel.DMChannel) == False):
for bannedWord in bannedWords:
if msg_contains_word(message.content.lower(), bannedWord):
await message.delete()
await message.channel.send(f"{messageAuthor.mention} tu mensaje sera revisado por un mod")
await self.client.process_commands(message)```
`Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\MiPC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\MiPC\Desktop\BD\cogs\CogC\deleter.py", line 37, in on_message
await message.delete()
File "C:\Users\MiPC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\message.py", line 1023, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Users\MiPC\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message`
I have no idea how to fix it xD
hi lol
the loop is iterating more than once and trying to delete the msg multiple times, which isn't possible
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\grace\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\grace\Desktop\CyberWare dependency\main.py", line 17, in on_message
await user.send("it works.")
AttributeError: 'NoneType' object has no attribute 'send'```
```py
@bot.event
async def on_message(msg):
if msg.webhook_id:
print(msg.content)
new_str = str(msg.content).lstrip("<@").rstrip(">")
user = bot.get_user(int(new_str))
await user.send("it works.")```
!d discord.Message.mentions
the user object is none
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
Use this (:
thx
how do you get avatar url in disnake, its different from discord.py for some reason
ok so how do i get the thing after the command ex; $command thing after the command
then ill remove the spaces and replace it with +
its gonna do
$google i am dog
its avatar.url
not avatar_url
don't be sending screenshots
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
alright
@bot.command()
async def google(ctx, word):
await ctx.send('https://www.google.com/search?q={}'.format(word))
hey how to check messages from an user?
like "if discord.Member_id == "id":
...
what you have only works for one word
async def google(ctx, *, word):
This should work for you
if message.author.id == your_id_var:
how do i replace the spaces with +
!d str.replace
str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
well, what can i do it for channels?
as channel id
?
oh
im pretty fresh in python
new
@bot.command()
async def google(ctx, *, word):
str.replace(" ", "+")
await ctx.send('https://www.google.com/search?q={}'.format(word))
@full lily doesnt work
Did you read this?
you removed word
And what did I say?
oh
hee hee
bro sorry
your word is a string
it is of the type string
so you can use string methods on it
str.replace is a string method
!f-strings :3
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Indeed :3
life lesson
@bot.command()
async def google(ctx, *, word):
word.replace(" ", "+")
await ctx.send(f'https://www.google.com/search?q={word}')
not working
What did you type in?
ok
basically $google i am dog
now you replace the " " with "+"
which does i+am+dog
now u make the i+am+dog into the https://www.google.com/search?q=i+am+dog
@cloud dawn
indeed
@bot.command()
async def google(ctx, *, word):
await ctx.send(f'https://www.google.com/search?q={word.replace(" ", "+")}')
This should work
i was thinking about that
alright ill check
ok all this time for a stupid command nobody will ever use
whatever i learned a lot
can someone help me? i'm getting the "unident does not match any outer indentation level" error on this:
if message.content.startswith("!del"):
encouragements = []
if "encouragements" in db.keys():
index = int(message.content.split("!del",1)[1])
delete_encouragments(index)
encouragements = db["encouragements"]
await message.channel.send(encouragements) <-(it's here)
where?
send a screenshot of it
alright
think about it
how can i make a slash command user view only (disnake)
what the point of my_secret?
in order to keep my bot's private token secret
huh
I'm making a discord bot
oh
no, i meant like doesi t serve any other use besides whats shown
cus its useless the way you have it
since client.run is already grabbing it
okay, but will it fix my problem?
whaats ur problem
unident does not match any outer indentation level
so fix the indentions to normal
how do I fix it?
restart IDE
I think he's using replit
Can we see the entire command?
sure
The indentation looks fine
Idk what to add to my bot
What do you have so far?
that's the maximum I could take in a screenshot
@bot.command()
async def help(ctx):
embed = discord.Embed(title="Hello, world!", description=":D", colour=0x87CEEB)
embed.set_author(name="vcokltfre", icon_url="https://avatars.githubusercontent.com/u/16879430")
embed.add_field(name="Field 1", value="Not an inline field!", inline=False)
embed.add_field(name="Field 2", value="An inline field!", inline=True)
embed.add_field(name="Field 3", value="Look I'm inline with field 2!", inline=True)
not working, embeds not working
I want to make a level system but cause I use replit to host it goes offline a lot so it's impractical
You never sent it
expected output:
Maybe use await ctx.send(embed=embed)?
ok maybe
await ctx.send(embed=embed)
Then don't use replit
Can u copy paste
ok
You need to remove the default help command
still 322025
I'm broke af so I don't know what else to host with
I try to do a command that DMs you every time you send it but it worked once. then it stopped working
wdym
options = starter_encouragements
if "encouragements" in db.keys():
options = options + db["encouragements"]
if any(word in message.content for word in sad_words):
await message.channel.send(random.choice(options))
if message.content.startswith("!new"):
encouraging_message = message.content.split("!new ",1)[1]
update_encouragements(encouraging_message)
await message.channel.send("New encouraging message added.")
if message.content.startswith("!del"):
encouragements = []
if "encouragements" in db.keys():
index = int(message.content.split("!del",1)[1])
delete_encouragments(index)
encouragements = db["encouragements"]
await message.channel.send(encouragements)
my_secret = os.environ['TOKEN']
client.run(os.getenv('TOKEN'))
!code please
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Actually it works with others which is the same code but the other one doesn't.
You need to remove the old one.
If you can shell out some money for a raspberry pi it's a good solution. You don't need to pay monthly for it
is there a way to make slash commands user only on disnake
Try bot or client.remove_command(“help”)
there isnt an old one
help_command=None when you initialize the bot object.
looks wrong here
There always is a default one :)
There is always a default one
what reallt
i want to say something for certain users that have something they need to activate. I want to say to the other users that they dont have anything to activate
Yes, try it yourself.
await message.channel.send(encouragements)
is missing 2 spaces at the start
ok
Send code
@bot.command()
@mods_or_owner()
async def proexpire(ctx, member : discord.Member = None):
if member is not None:
channel = member.dm_channel
if channel is None:
channel = await member.create_dm()
await channel.send("You have a pro membership that will expire soon! To enable the pro membership use `v!pro`")
else:
await ctx.send("Please mention the user you want to notify!")
@bot.command()
async def pro(ctx, member : discord.Member = None):
if member is not None:
channel = member.dm_channel
if id == "674960649662627850" or "608575327811272704":
if channel is None:
channel = await member.create_dm()
else:
await channel.send("You have activated your pro membership!")
prorole = ctx.guild.get_role(911248795382194201)
await ctx.author.add_roles(prorole)
else:
await ctx.send("You have no pro packages to activate!\nYou can buy pro packages at our website, or win them by a giveaway.")
Hey @slate swan did you already do client or bot.remove_command(“help”)
What is @mods_or_owner()
a custom function i made for owner or mods
it doesnt bother the code
did not work
gg bois
You can just do member.send() and it should create a dm if there isn't one already
Did it help?
yes
🙂
bro ur so good
It’s all good
i want to send it in a dm
There is already a help command built in so you always have to remove it
yesyes
I do not have the money to shell out
so what do I do?
so i remove the
if channel is None:
channel = await member.create_dm()
?
Ye and instead of channel.send do member.send
You should just be able to do await ctx.message.author.send()
ctx.author
Or that
the line of code i sent before saying it will be removed is okay.
What about the start?
if member is not None:
channel = member.dm_channel
this
Ye remove the channel = member.dm_channel part
lemme try it now
Ignoring exception in command pro:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\Vaggelis\Coding\Bots\VDP's Utilities\main.py", line 105, in pro
await member.send("You have activated your pro membership!")
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\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\user\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\user\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: 'NoneType' object has no attribute 'send'```
Error
the second command has problem
Is the first one fine?
yeah
Can u send code for just second one
The member instance is none which is why it’s raising the error
@bot.command()
async def pro(ctx, member : discord.Member = None):
if id == "674960649662627850" or "608575327811272704":
await member.send("You have activated your pro membership!")
prorole = ctx.guild.get_role(911248795382194201)
await ctx.author.add_roles(prorole)
else:
await ctx.send("You have no pro packages to activate!\nYou can buy pro packages at our website, or win them by a giveaway.")
What's id?
the userid
that’s probably why the error is raising
^
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
so for disnake to remove the help command its help_command=None but when i run my own help command the default one still pops up :/
and you know that or returns the first truthy value
ids are also ints not strings
It doesn’t work how you think it does
^
i did that. still didnt dm
Did you make the IDs ints?
!or
and also got error
wait no
you can set a local variable
They should be ints so remove the "
anyone know this?
Sorry I don't use disnake
what do you use?
Try client.remove_command('help')
about this?
hm.. still sends the default message, ALONG with mine lol
weird since mines named help and the bloody thing still sends mine
In ur else statement it's still ctx.send
Also I noticed something. I also put my id in the example that binds send before
users = [id, id]
but it used the else
yeah what do i put instead of ctx.send?
What's ur if statement
member.send
@bot.command()
async def pro(ctx, member : discord.Member = None):
prousers = [674960649662627850, 608575327811272704]
if member in prousers:
await member.send("You have activated your pro membership!")
prorole = ctx.guild.get_role(911248795382194201)
await ctx.author.add_roles(prorole)
else:
await ctx.send("You have no pro packages to activate!\nYou can buy pro packages at our website, or win them by a giveaway.")
What error?
wait
Ignoring exception in command pro:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Desktop\Vaggelis\Coding\Bots\VDP's Utilities\main.py", line 105, in pro
if member.id in prousers:
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\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\user\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\user\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: 'NoneType' object has no attribute 'id'
That means member is None
pp
yeah what changes do I have to do?
alright
One sec let me make this cmd
???
Wrong channel
cant find the one
colour should not be equal to a list
That's is not how you go about doing that
OK SORRY BYE
Also it doesn't do colours like that
changes?
why bro
also
y isnt it working
OH
I GOT THE FORMAT WRONG OMG SO SORRY
@client.command()
async def pro(ctx, member: discord.Member = None):
prousers = [485442448244342786, 608575327811272704]
if member.id in prousers:
await member.send("You have activated your pro membership!")
prorole = get(ctx.guild.roles, id=911248795382194201)
await member.add_roles(prorole)
else:
await member.send("You have no pro packages to activate!\nYou can buy pro packages at our website, or win them by a giveaway.")
ok why isnt it working
hexcode = ['FA291A','FA701A','FAD11A','7BFA1A','1AB7FA','831AFA','FA1AFA']
@bot.command()
async def help(ctx):
embed = discord.Embed(title="Help command", description="Lists of commands", colour=random.choice(hexcode))
does anyone know anything about a good vps for a discord bot under 5$? (less preferably) I'm looking and vultr and galaxygate. i'm really looking for a fast response time from my bot and the lowest ping possible.
the example
make sure you have from discord.utils import get @kind wind
"embed = discord.Embed(title="Hello, world!", description=":D", colour=0x87CEEB)"
thats their code
ok mine is randomizee
whats a VPS
like a thing thatll make ur bot
active 24/7
a way to host your bot 24/7
i've tried it, not much of a fan
heroku has a roughly 7-day downtime at the end of each month
discord.py's discord?
give me a sec
ngl i would like a fiver
Whats he asking
he wants a randomised colour for his embed using a list
It is possible
.
!d list.shuffle
What is it?
Or just use discord.Colour.random()
i think he wants to use those specific colours
help cmd
You need to store colors as 0xHEX and not strings
Oh
Then you can use random.choice on the list.
!d random.shuffle
okokokokokokokok
random.shuffle(x[, random])```
Shuffle the sequence *x* in place.
The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function [`random()`](https://docs.python.org/3/library/random.html#random.random "random.random").
To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.
Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.
Deprecated since version 3.9, will be removed in version 3.11: The optional parameter *random*.
Or random.choice
ok letme try
how do u store 0xHEX as a non string
Just like anything else?
!e
import random
l = [0xFFFFFF, 0xFF00FF, 0x00FF00]
print(random.choice(l))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
16777215
It's basically the decimal value.
wait like ths
No, not as strings as I said.
Remove the ''.
kk
didnt know u were allowed
As you can see from that, it's basically a number being stored.
You could write the decimal value of each color instead of 0x..., it's just not convenient.
i never knew this
Very smart guy ik
ikr
Yours contains strings, not hex numbers. Thats the issue.
You're trying to set color to "00101F" for example, which is invalid.
It expects color to be set to 0x00101F

the issue is done
it works
@slate swan Please behave yourself.
i am behaved
what u are asking for sounds like it would be against a ToS
No you are not, look at the chat, please keep it civil and stop asking for us to make a spam bot or offer money.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
<@&831776746206265384>
@slate swan This is not something you may ask for help with in this server.
kk
What happened here
idk
He removed most if not all messages.
I see that
@final iron What are you doing :3
Finished my homework and discord bot time
Either going to implement documentation command, youtube search command or add a system so users can see how many commands were ran
print(interaction.message.embeds[0].fields)
[EmbedProxy(value='Smaug#6390', name='MEMBERS', inline=True)]
how i can get only the field value?
Gonna make the docs command aswell with autocompletion :D
Just made my error handler. Any comments? https://paste.pythondiscord.com/ukobanuwuc.py
interaction.message.embeds[0].fields[0].value
Basically what I was going to do
How are you going to implement autocompletion?
I've seen it used in slash commands but I've never understood it
thanks panda
Prob the same as the pypi autocomplete i did a while back
async def autocomplete_pypi(inter: ApplicationCommandInteraction, string: str) -> List[str]:
return sorted([lang for lang in PACKAGES if string.lower() in lang.lower()][:25])
Using a list limiter [:25]
@slash_command(name="pypi")
async def get_package_info(
self, inter: ApplicationCommandInteraction,
package: str = Param(autocomplete=autocomplete_pypi),
hidden: bool = True
) -> Message:
Still have to think about what docs ill use and i need to make some kind of recursive dir function.
how many resources does a discord bot take?
Depends severely on what you are doing, how many guilds there are and how many users.
if im using it on 1 guild, and like 5 users
Message can also be a factor if only large messages are send.
What is autocomplete_pypi?
😔 sorted is O(n log n)
Likely not that much
Custom function.
It works :3
could that host like 3 bots? or just 1
I want my bot to scan a channel and take all the images and videos and append it in a list and then send it@bot.command(name="meme") async def on_message(message, ctx : commands.Context): if message.channel.id == 699577970117050399: meme_list = [] if message.attachments.url.endswith('png') or message.attachments.url.endswith('jpg') or message.attachments.url.endswith('jpeg') or message.attachments.url.endswith('mp4') or message.attachments[0].url.endwith('gif'): url = message.attachments.url meme_list.append(url) list_len = len(meme_list) rand = random.randrange(list_len) await ctx.send(meme_list[rand])
I understood that
Most likely yep.
Could you explain how I would create an autocomplete system?
Sure, but I can make a hash map implementation of that probably which would make it O(1)
Wdym system? It takes a list.
package: str = Param(autocomplete=autocomplete_pypi) will be assigned as suggestion.
Not too familiar what exactly do you mean?
Hash map as in dict
What's not good about sorting it then?
I took a look at the documentation
Looks interesting
How do you get a list of the pypi packages?
Wait
nvm I'm dumb
Whenever someone enters a valid pypi i add it to the database.
Not going to add the whole pypi database.
Do you know pypi has an API
I'm using that yeah. But i'm not going to make request on auto completion lol
how do i host a galaxygate bot
Idk i use a different host it twice as expensive as your bot so much better.
what host
Oh thats smart
Can I implement that myself?
Actually
Ill just create a task that calls the entire database
https://github.com/Pandabweer/dispy-discord-bot/blob/main/exts/info/pypi.py it's running on a json rn (don't judge i'm still creating the wrapper for postgre) but you can edit that and just replace PACKAGE with whatever.
never used disnake before, or buttons. why does this still return a "interaction failed" even though the embed changes?
class Button(disnake.ui.View):
@disnake.ui.button(style=disnake.ButtonStyle.blurple, label='Click Me')
async def button(self, button: disnake.ui.Button, interaction: disnake.Interaction):
embed = disnake.Embed(title='Clicked!', description='You clicked the button')
await interaction.message.edit(embed=embed)
@bot.listen('on_ready')
async def on_ready():
print('Ready and roaring to go!')
@bot.slash_command(description="Responds with 'World'")
async def hello(interaction):
await interaction.response.send_message("World", view=Button())
You have to respond to an interaction otherwise discord API considers it dead/failed
You can send a DEFER response payload
So, just getting started with slash commands
How would I use them inside a cog?
I'm using disnake
Actually I think I figured it out
slash_command
So since the slash commands don't get registered instantly, should I only register them in my guild until I know they're working and then release them to the public?
Yeah exactly
test_guilds=[926115595307614249, 561662622827806721]
Inside the class constructor
Okay well, first error
SyncWarning: Failed to overwrite commands in <Guild id=926959868248739840> due to 403 Forbidden (error code: 50001): Missing Access
warnings.warn(
Whenever I run the bot
Ik. I'm reading the docs
Ohh you need to enable application command when the bot joins
What do you mean?
Basically
https://discord.com/api/oauth2/authorize?client_id= bot_id_here &permissions=8&scope=bot%20applications.commands

For slash yeah
Alr
You need the application command.
Its working now
how do you get an image from an embed
embed object?
oh hi panda, im trying to make a command to go through a channels message history and save an image in an embed, but i dont know how to get the image from the embed
So from a message object
yeah, say a bot sends a embed with a image in the embed, i wanna be able to get that image and save it
i know how to save files, just not files in embeds
Never done this looking at the docs
alright
Im going through my bots autoposting channel and planning on adding some of those images to an api
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
if message.embeds:
for embed in message.embeds:
if embed.image:
if embed.image.proxy_url:
await embed.image.save(os.path.join(folder_name, embed.image.url.filename))
``` this is what i have so far, i keep getting `CommandInvokeError: Command raised an exception: TypeError: join() argument must be str, bytes, or os.PathLike object, not '_EmptyEmbed'`
Let's try to get the urls first
how do i make a thing that prints when the bot is online? in the console
@bot.event
async def on_ready():
print("we're online!")```
ty
np
its {0.user} for the bot right?
umm
for embed in [embed for embed in message.embeds if embed.image]:
print(embed.image.url)
Old method of using .format yeah
like if you're using .format and you gave .format your instance of bot, then yeah...
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
lemme try this
Modern method
You don't have to check if a list is empty or not with if since an empty list will be iterated the for loop will do nothing.
so py @bot.event is the right way to make events now?
@bot.listen()
alright ty
!d disnake.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_ready "disnake.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
yeah this worked
Nice let's combine our code
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
for embed in [embed for embed in message.embeds if embed.image]:
print(embed.image.url)
# await embed.image.save(os.path.join(folder_name, embed.image.url.filename))
embed.image does not have .save though
yep this works
lemme try with the save now
No documentation found for the requested symbol.
!d disnake.Member.banner
property banner```
Equivalent to [`User.banner`](https://docs.disnake.dev/en/latest/api.html#disnake.User.banner "disnake.User.banner")
!d disnake.Asset.url
property url: str```
Returns the underlying URL of the asset.
aka ```
member.banner.url
Gotta agree that the docs are kind of weird about that one.
Best fork there is :3
What is the best fork then?
CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'filename'``` @cloud dawn
Send your current code
@commands.command(name="download")
@commands.check(permissions.is_owner)
async def download_channel(self, ctx, channel: discord.TextChannel, folder_name):
if not os.path.exists(folder_name):
os.mkdir(folder_name)
if not channel:
await ctx.send("You need to specify a channel!")
return
await ctx.send(
f"Downloading all files in {channel.mention}"
)
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
for embed in [embed for embed in message.embeds if embed.image]:
await embed.image.save(os.path.join(folder_name, embed.image.url.filename))
ill add an asyncio sleep whenever this works
@commands.command(name="download")
@commands.check(permissions.is_owner)
async def download_channel(self, ctx, channel: discord.TextChannel, folder_name):
if not os.path.exists(folder_name):
os.mkdir(folder_name)
if not channel:
await ctx.send("You need to specify a channel!")
return
await ctx.send(
f"Downloading all files in {channel.mention}"
)
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
for embed in [embed for embed in message.embeds if embed.image]:
await embed.image.save(os.path.join(folder_name, embed.image.key))
``` What about this
lets see
I'm hosting my bot on my phone
The more commands that get used at a time across a number of servers, would that end up making the phone's battery die faster if it were just idle?
yes
my bot got api blocked, how do i unblock it and avoid that?
To unblock it you gotta wait and to avoid it don't make too many requests.
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
CommandInvokeError: Command raised an exception: TypeError: join() argument must be str, bytes, or os.PathLike object, not '_EmptyEmbed'```
same error like before
@bot.command()
async def hack(ctx, *, word):
embed = discord.Embed(title=f"Hacking {word}", description="Starting the main frame", colour=0xFAEB1A)
await ctx.send(embed=embed)
not working
word is a required argument that is missing
moderation commands, ping command, error handler, setstatus
[prefix]hack word?
So, provide a word?
so are u doing $hack something
$hack nasa
Well, you have a *,
yes
ah yeah remove the *
ok but what if the guys
!d os.path.join
os.path.join(path, *paths)```
Join one or more path components intelligently. The return value is the concatenation of *path* and any members of **paths* with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
name is like max (something)
You tag him?
rip i just leaked my name
It'll still count as one.
rip lol
im not on the internet anywys
its saying the embed is empty, i dont think its a path.join issue
what counts as making a request
@bot.command()
async def hack(ctx, word):
embed = discord.Embed(title=f"Hacking {word}", description="Starting the main frame", colour=0xFAEB1A)
await ctx.send(embed=embed)
You would do: $hack @slate swan
anything that interacts with discord
sending a message, connecting to a channel, even errors
is it because i was starting and restarting too much
is there a way that like
oh yeah probably, connecting makes a lot of requests
yeh that's possible
@commands.command(name="download")
@commands.check(permissions.is_owner)
async def download_channel(self, ctx, channel: discord.TextChannel, folder_name):
if not os.path.exists(folder_name):
os.mkdir(folder_name)
if not channel:
await ctx.send("You need to specify a channel!")
return
await ctx.send(
f"Downloading all files in {channel.mention}"
)
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
for embed in [embed for embed in message.embeds if embed.image]:
await embed.image.save(f"./{folder_name}/{embed.image.key}.png")
i cant save it with .png, some of the files are gifs too
hence the .filename
Then you gotta mimetype check it
uhh
@bot.command()
async def hack(ctx, word=None):
if word == None:
await ctx.send(f"{ctx.message.author.mention}, You can't hack **air** bro.")
else:
embed = discord.Embed(title=f"Hacking {word}", description="Starting the main frame", colour=0xFAEB1A)
await ctx.send(embed=embed)
@slate swan
bro what
idk
if arg is None: do that instead man
i just took ur statement
is_animated() is also there lemme just..
probably shouldnt be a programmer i suck
you added a whole new argument into your command, just take the code I sent LOL
We all start somewhere bro
nothing wrong with being bad at something you just started
Damn. I actually like slash commands
Fr
same..
sure
I think Discord just released them too early
why not
@commands.command(name="download")
@commands.check(permissions.is_owner)
async def download_channel(self, ctx, channel: discord.TextChannel, folder_name):
if not os.path.exists(folder_name):
os.mkdir(folder_name)
if not channel:
await ctx.send("You need to specify a channel!")
return
await ctx.send(
f"Downloading all files in {channel.mention}"
)
async with ctx.channel.typing():
async for message in channel.history(limit=None, oldest_first=True):
for embed in [embed for embed in message.embeds if embed.image]:
await embed.image.save(f"./{folder_name}/{embed.image.key}.{'gif' if embed.image.is_animated() else 'png'}")
I'm pretty sure slash commands got released early because of the d.py issue
That it was expiring or something like that
What?
..?
ah that makes more sense
That's what I was told
We're third party Discord doesn't care
I just think discord didn't realize how bad they were at the time
ok i dont understand
discord doesn't realize how bad they are sometimes
@bot.command()
async def hack(ctx, word, arg):
if word is None:
await ctx.send('Can\'t hack nothing')
embed = discord.Embed(title=f"Hacking {word}", description="Starting the main frame", colour=0xFAEB1A)
await ctx.send(embed=embed)
I gave you the code earlier man.
word is required
If a user doesn't input it, it throws an error
oh kk
So it'd be $hack stuff stuff
CommandInvokeError: Command raised an exception: TypeError: '_EmptyEmbed' object is not callable```
still empty, i even checked the message and its not empty
how do u guys sell ur bots
you don't?
if you do
We don't
none of us do
okok why not
imo code isnt worth a price
learning and earning
At most, people will gate certain features behind a paywall
If you sell bots you're strange, cause people who sell bots, don't realize, half of the bots already created, beat their bot in every single shape, way and form.
err bit wide this statement
yes but 10$
still bro
You can't really earn anything by selling your bot.
lemme rephrase, anyone can learn how to code, so it shouldnt be locked behind something if you can just learn how to do it yourself for free
id sell my liver for 10$
😐
Nobody will buy it
ok
except for a command that predicts when elon musk will release flying cars
Nothing
how about you use that $10 and buy some nitro
Most if not all bots are open source
The Discord bot space right now isn't originality. Its who can pack the most commands in to a single bot and still have a good user interface
@cloud dawn, whats weird about this is that when we printed, it worked just fine, it got the image links and everything, it just doesnt wanna save
I wouldn't suggest it
At this point i'd just make my own async aiohttp request lmao
You're going to end up with a ton of files
ughhh
Kind of glad they added a 50 command max on slash bots. A lot of people were complaining like my bot has 230 commands uwu
Like who needs that many.
ok but why learn programming in the first place
Wait
Question: Is it possible for a bot editing a role/message that it just breaks and the editing just stops and no matter what you do it stays that way?
what will it teach me
Because you can create your own stuff. And there are other things than Discord bots.
If there is a 50 command cap on slash commands doesn't that fuck over the verified bots since after april they can only use slash commands?
Since after like April they can only use slash commands?
Like re-edit to the original msg?
can python work with css3
yeah
You'll get there
Python can work with all languages.
LOL
That it basically just "freaks out" and stops working
okokokokokokok
That's like, 10 percent of my bots commands
?
python > every other programming language thats ever created ever
uhhhhhhhhhhhhhh
Freaks out?
like use python instead of javscript
That's up to you man
rlly
In certain situations, yes, in certain situations, no
Like it's just like this is going way to fast for me imma just stop
Well no since Python is backend and js is front end.
We're only here to help with python, as this is a python discord.
If there is a 50 command cap on slash commands doesn't that fuck over the verified bots since after april they can only use slash commands?
Or does the limit increase for them
Just try to explain it and we will give an answer.
Any bot that doesn't have slash is gonna get fucked.
Unless you are not verified
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
@cloud dawn okay so embed.image.save just doesnt work, printing the image url's work fine
Yeah like i said i would just my own aiohttp request.
You can then also send the whole list to a function and tell the user it is downloading in the background.
For example: You code a bot that can edit messages REALLY fast and it just breaks
If you're editing messages really often you're going to get rate limited
Well you would get rate limited so it wouldn't be possible
It's like the grey messages you get when spamming
But then the bot would just say no
Oh alright thanks, I was just curious
?
Please keep it on topic, a bit off topic is fine but this is just random.
Does bot.commands include slash commands?
from disnake.ext.commands import slash_command
is discord py outdated
Not likely @final iron
Looks like you would need this
!d disnake.ext.commands.InteractionBot.global_slash_commands
property global_slash_commands: List[disnake.app_commands.SlashCommand]```
The client’s global slash commands.
idk if they return if you got test guilds on though
any ideas why my slash commands aren't working?
[WARNING] Failed to overwrite commands in <Guild id=930562118359588904> due to 403 Forbidden (error code: 50001): Missing Access
they had the above error, here's an example of one:
@commands.slash_command(
name="ping",
description="returns bot latency",
guild_ids=[923632089834864690, 930562118359588904],
)
async def get_ping(self, inter: ApplicationCommandInteraction):
em = disnake.Embed(
title="Pong! 🏓",
color=0xD3D3D3,
description=f"Latency: {round(self.client.latency * 1000)}ms",
)
await inter.send(embed=em, ephemeral=True)
i'll ask in a help channel if none of y'all know
what lib are u using btw
i told u already, disnake
whats guild ids
the one you have and the one i own
i made it just those because
it said it would take like 12h to register globally soz
you can manually do it easier than that but it just didn't want me to ig
globally register a slash command jeez
¯_(ツ)_/¯
they're gonna be required eventually soz
if i can learn it that sames u some trouble
Did it work before?
Has any slash command worked?
in those servers by other bots, yes
not my own tho, this was the first time i tried to set up my own
yeah like
Explained this today to some1 else aswell -> https://discordapp.com/channels/267624335836053506/343944376055103488/932400727186362488
EVER has ANY SLASH COMMAND EVER WORKED?
ouu
Slash commands are pretty nice
that make them so special
obtuse to work with though
there is just no clean way to do them in python!
This is obviously more suited for javascript wrappers
😔
Disnake did a pretty good job
Bro... just look at that decorator
yuck
disnake is nice
😂
but it works
🤷 slowmode annoying
right?
ok thats
tbf he/she could have passed the test guild inside the bot constructor.
fair enough but what about it not being ctx
Wouldn't make sense to call it ctx
Does disnake even support command options
It does.
😂
Andy just likes to be thorough.
Do you know what I'm asking by command options
/j






