#discord-bots
1 messages · Page 1038 of 1
That is an api response
that's not the reason but yes
Now I feel dumb
why because you feel like getch should be the only implementation of getting objects?
yeah, the reason is that it is a coroutine, and that is, because it makes an asynchronous api call
yea~, making the api calls only when really needed is more preferable
and.....it didnt do anything
atleast for me.
yeah it would lower traffic from people making useless api calls but i feel like they should still be a thing as it can be used in some cases
true. also if the bot is in the server bot.get_guild should always work
can i see your PermissionOverwrite
yo bro 🗿the id should be the role id/ user id
not a channel id
lmao, how do I set it for everyone 😔
guild.default_role
hm
||everyone role's id is same as the guild id||
context.guild_id preferably
not sure if that's true
weird, but thanks
you're correct, TIL
discord/guild.py lines 868 to 872
@property
def default_role(self) -> Role:
""":class:`Role`: Gets the @everyone role that all members have by default."""
# The @everyone role is *always* given
return self.get_role(self.id) # type: ignore```
nice to know what's behind that attribute ig
still, I would always prefer guild.default_role.id over guild.id when trying to get the @everyone role id
yes you are being dumb again, notice the type kwarg
pffftttt, sorry
.....Type.MEMBER for a role
so trustful 😭
I cant 😭
i cant cuz im in school🏂
and
and school is for studying so stay in school kids so your examples arent as bad as Robins!
gn
😐
why boolie robin 
async def on_message(message):
if message.channel.id == 970295286851305482:
await message.delete()
else:
return
suggestEmbed = discord.Embed(colour=0xfecb01)
suggestEmbed.set_author(name =message.author, icon_url= message.author.avatar.url),
suggestEmbed.add_field(name= 'Ötlet', value= message.content)
message = await message.channel.send(embed=suggestEmbed)
await message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
await message.add_reaction('\N{CROSS MARK}') ```
Hello. When I write in the channel (970295286851305482) I get this error
Change it to
msg = await message.channel.send(...)
await msg.add_reaction(...)
Eh
Wait I think I know the issue
It's cz u r sending the message again to the same msg and the bot is deleting it again
how to you use !discord ?
Add this line at the top:
if message.author == bot.user:
return
!d discord ?
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
You need the class that a method or property is of
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
There
ok
Ive just never used the bot before
!d disnake.Role
class disnake.Role```
Represents a Discord role in a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild")...
(slap) BAD BOT!
It does require you to know the classes methods and attributes are part of so you’ll usually see people helping using those commands
Like I learnt from seb and Robin
ok so i have this code to uh set log channels for different servers
`
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
logchannels[str(ctx.guild.id)] = logchannel
with open('logchannel.json', 'w') as f:
json.dump(logchannels, f)
await ctx.send(f"Changed the logchannel to {logchannel}")```
and when i set it in a event :
```@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"deleted message!")
embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
logchanneld = bot.get_channel(int(logchannel))
await logchanneld.send(embed=embed)``` can anyone help?
yes but my issue is that logchannel is used as a parameter in a def function and i cant call it in anywhere else so is there like anyway i can call it somehow? and i cant use global for that because it is used as a parameter
when using defs does it matter what you name it ?
I'm making a discord bot and I made a embed but it's not working I tried to make a new bot with few commands like ping and test but the bot is not replying
@bot.command()
async def help(ctx):
if ctx.channel.type != discord.ChannelType.private:
if ctx.channel.id == 973394572627562506:
embed=discord.Embed(title="Help", description=".", color=0x71368A)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.add_field(name="tt", value="tt", inline=True)
embed.add_field(name="ats", value="fw`", inline=True)
embed.add_field(name="wf", value="awf", inline=True)
embed.add_field(name="he", value="wf", inline=True)
embed.add_field(name="ja", value="ge `(channel)`", inline=True)
embed.add_field(name="Twitch ", value="gw", inline=True)
embed.add_field(name="Twitch", value="mhm", inline=True)
embed.add_field(name="Twitch", value="gww", inline=True)
embed.add_field(name="Twitch ", value="wgw", inline=True)
embed.add_field(name="Twitch ii", value="twtw`", inline=True)
embed.set_footer(text="Made by Flame 'Em -_-rormommemm-_-#4779")
await ctx.send(embed=embed)
else:
await ctx.message.delete()
can someone help me the bot is not working
at all
I made a whole new bot with a ping pong command
doesnt work idk whats wrong with discord.py
send all bot code without the token
ok
Most likely not something wrong with discord.py
token = "no"
prefix = "!"
import discord
from discord.ext import commands
import requests
import json
bot = commands.Bot(command_prefix=prefix)
bot.remove_command('help')
@bot.event
async def on_ready():
print("Bot is ready")
await bot.change_presence(activity=discord.Game(name="Bot prefix: !"))
@bot.command()
async def help(ctx):
if ctx.channel.type != discord.ChannelType.private:
if ctx.channel.id == 973394572627562506:
embed=discord.Embed(title="Help", description=".", color=0x71368A)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.add_field(name="tt", value="tt", inline=True)
embed.add_field(name="ats", value="fw`", inline=True)
embed.add_field(name="wf", value="awf", inline=True)
embed.add_field(name="he", value="wf", inline=True)
embed.add_field(name="ja", value="ge `(channel)`", inline=True)
embed.add_field(name="Twitch ", value="gw", inline=True)
embed.add_field(name="Twitch", value="mhm", inline=True)
embed.add_field(name="Twitch", value="gww", inline=True)
embed.add_field(name="Twitch ", value="wgw", inline=True)
embed.add_field(name="Twitch ii", value="twtw`", inline=True)
embed.set_footer(text="Made by Flame 'Em -_-rormommemm-_-#4779")
await ctx.send(embed=embed)
else:
await ctx.message.delete()
bot.run(token)
You know I think you could really simplify this with a dict
Can you help me fix it
Without any traceback or knowing what the issue is, no
my issue is there any fix for it as well?
Its not printing anything
wtf
In console or sending the embed in discord?
both
how do you get bots to give users roles that the user cant chose
add_role should work like usual
k
can someone tell me how to make commands like a kick command?
@bot.command() doesn’t work
Same dude
!d discord.Guild.kick
await kick(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`kick_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") permission to
do this.
How do I fix this
@bot.command()
@commands.has_permissions(ban_members=True)
async def giverole(ctx, member.mention, *, role:discord.Role):
await member.add_roles('Spectors Journey')
i get an error if i made it like this
Look at your 2nd argument
It has to be name: typehint format
member: discord.Member
how do I make it to be the message author ?
ctx.author

Actually nvm
Misunderstood
Use that to get the user who should be getting the role
so would I just
discord.Member = ctx.author
@bot.command()
^IndentationError: unindent does not match any outer indentation level
how can i fix it
do you have a prefix ?
Should be using commands extension
have you imported discord.ext.commands
yes if you mean this import discord.ext
from discord.ext import commands,
do you have anything after the ,
tasks
@sick birch what is that and how do I fix it
ok I dont see why it dosent work
What tutorial are they bringing on_message practice from 🤦♂️
Quickstart or smth
Read the docs, not the YouTube tutorials
OK how to fix?
I’m not sure why any tutorial would recommend using on message for commands
@sick birch
how do I get the user of the message to used ?
@bot.command()
@commands.has_permissions(ban_members=True)
async def giverole(ctx, member: ctx.author, *, role:discord.Role):
await member.add_roles('Spectors Journey')
Most tutorials are like that though (d.js, jda)
but d.py has a commands extension so good point
yeah dpy is much more high level it seems
Especially djs is a lot more lower level and closed to the API
It’s a “true wrapper” you could say, while dpy is more of a framework
can anyone help how can i use logchannel for everywhere
Typehints need to be valid classes
what do you mean by that ?
Have you learned how to use typehints?
'Spectors Journey' replace this with 'role'
member: discord.Member
Typehints power Dpy’s commands extension, so knowing how they work is paramount
I guess your answer is no
Well @austere gust gave you the answer but I’d strongly suggest learning how to use them so you don’t make things harder for yourself
btw does it matter from what website it is
What?
@sick birch do you have any idea?
I’m guessing you deleted the message before adding a reaction to it
yo my discord is hard bugged and a could not see any message what was the - how do I do that?
i think what hunter said there is the issue, the bot deletes the message it sends immedietely
!d discord.ext.commands
No documentation found for the requested symbol.
hmph
yeah, but how should I fix it
@austere gust i guess it's something wrong with your variable, try changing the name of the variable
hunter said it, add that part of code to your event
just check if the message author is your bot, and if so don't delete it
anand gib me reaction permissions too
i don't have the power to do that
return```
sadge
This?
Try assigning a different variable for the message sent than that for the event's message.
that
that's what i am saying
to the very start
guess i got ignored 😦
wut
done
msg = await message.channel.send(..)
cuz it just doesn't make sense what you both said vemv
no, not ignored, thanks 🙂
That’s the commands extension
@austere gust try this
Reading the documentation is the best way to start
fixed by hunter's method thanks anyway
Not sure why it’s doing that but if you go on the documentation you’ll find it
yeah
the module itself doesn't have a symbol on the docs so the docs command can't fetch it i guess
Wrong channel
here the best way to start is coming here and start asking random question without even opening the docs
^
i don't think the people helping you here appreciate that attitude though :p
You got it
Usually i'm the one who help them 
That’s alright but we as helpers (not the role, just people who provide help) should redirect them to the right docs first
Always do that 
I totally understand that docs can be intimidating first but we can ease that by pointing them in the right direction
sad part is the docs won't help unless the person knows oop
That’s a bit of an unpopular opinion among the discord bot community
imo the dpy docs are really good once you figure out how to properly navigate it. if it's your first time on the page it'll look like a massive dump of data and you won't know what to search for in the first place
of course you need something to start with
if, for example, you take the examples written in the d.py or other forks github and search in the docs the methods that you don't understand it will be quite simple to learn those package
and to learn how to navigate through the docs
the code you sent and the error are different
that too ^
!e
test_str = "uwu"
if test_str.startswith("uwu"):
print("totally uwu")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
totally uwu
when I do that it just does nothing - sends no console error and no message back
hunter dont comment on my example
are they how? it says the error is on line 36 and if message.content.startswith == '-s stats': is
test_str = "uwu"
if test_str.split()[0] == "uwu":
print("totally uwu")
Ezzz
and the error you sent has message.content.str.startsWith
as ashley says, it's a method you have to call, not check for equality
message.content.startswith("whatever")
imagine
ew ew ew
why even use split when startswith exists (for that case)
Thanks
test_str = "uwu"
search_string = "uwu"
if test_str[len(search_string)] == search_string:
print("totally uwu")
will it work with this then..
Idk, was bored so tried smth new
U didn't slice tho...
U indexed it
I am just ignoring it now since u r never gonna stop saying that
ew ew EW
u neither... slicing is this lst[x:y:z]
I agree
Ik...
I didn't want to slice tho 😐
r'^(uwu)' 😳
I am using split and comparing the first element of the list
now it says this
content
isn't that a webhook?
you mistyped content
and i'm searching if the string i want is in the first characters of the length of that string into another string 
just send multiple embeds, those are two diff embeds not the same ones
👋
👋
if message.content.startswith("-s stats"):
...
and I suggest using commands
whats different in that field? its normal
don't spoiler ashley, he is learning 
what are you takin' bout
"spoiler"[:-2]*
That is two different embeds
You can see the separation
You can even see the timestamp is for a second msg
ew
same
staph
no
oh man next time I see uwu imma go donate my eyes to a machine learning algorithm
How cringe can u even be @slate swan
Welcome to my cult
How do I fix this
@bot.command()
async def join_spectors(ctx, member: discord.Member):
role_id = 'Spectors Journey'
msg = f'{member} has joined {member.add_roles(discord.Member, role_id, True)}'
await ctx.reply(msg)
Okay lets stop it now haha
u need an ID, not a name
Wtf
the id of the role ? right how do i find that
Nvmd
Go on discord, find the list of roles in your server, right cilck > copy ID
That
oh ok im just dumb 🙂
Yall think if there was an example usecase for every single function on the docs it would help ppl?
Probably not
so add_roles returns the role that was added? 
it's also way too much work
Sometimes I feel like the more info we get the harder it is to think for ourselves and we get confused when the time comes to implement something different from what we saw
wayyy
discord.py also mentions that it's not a library intended for beginners, so having examples for every usecase would go against that
Having some amount of knowledge can greatly help you when making discord bots w/ discord.py
That's true but that warning doesn't really prevent much these days
I back u
guy i want help....
I'm currently using discord-slash..now i wanna tottaly uninstall discord-slash and i wanna install pycord and want it to work....idk how to do it
copy Id isnt their its only view server as role
pip uninstall <module_name> in yr cmd prompt
That and for a lot of other API operations that create something: .send() returns the new message, .create_text_channel() returns the created text channel, etc
use pip to remove the package the same way you added it
You need to enable developer mode on your account then
^
when i use nextcord for discord bot, it gives me
RuntimeError: Event loop is closed
is your bot token correct?
Click on the little cog to the right of your name on the bottom left hand corner, then "Advanced", then "Enable developer mode"
yep
Send the entire traceback
and remove any token(s) from it ^
^^
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
username is deleted
That doesn't seem like the full traceback because everything there is part of the library's internals
Usually when your traceback gives code pointing to the library's internals it's caused by something in your code
it shows this traceback when i run it
You're 100% sure that's everything in your terminal?
let me recheck
i missed this: Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C07FDEE440>

Send ur code fam
Great, now it's spewing memory addresses
import nextcord
from nextcord import Interaction
from nextcord.ext import commands
testingServerId = N/A
intents = nextcord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "!", intents=intents)
@client.event
async def on_ready():
print("The bot is now ready to be used")
@nextcord.slash_command(name = "hello", description="Replies with hello")
async def hellocommand(interaction: Interaction):
await interaction.response.send_message("Hello")
client.run('N/A')
/hello basic command
N/A means im not telling you
@sick birch is the member.add_roles correct
@bot.command()
async def join_spectors(ctx, member: discord.Member):
role_id = '973960685413343253'
msg = f'{member} has joined {member.add_roles(discord.Member, role_id, True)}'
await ctx.reply(msg)
Well this is interesting
Is your internet alright?
role_id needs to be an integer
ok so i have this code to uh set log channels for different servers
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
logchannels[str(ctx.guild.id)] = logchannel
with open('logchannel.json', 'w') as f:
json.dump(logchannels, f)
await ctx.send(f"Changed the logchannel to {logchannel}")```
and when i set it in a event :
```@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"deleted message!")
embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
logchanneld = bot.get_channel(int(logchannel))
await logchanneld.send(embed=embed)```
the issue is i can not call it in the event
logchannel
and i cant use it as a global variable because it's set as a parameter under the def function already
member.add_roles(discord.Member, role_id, True) is incorrect
Cu the traceback is entirely asyncio so I'd guess it's occurring when ur bot is tryna connect
whats the correct one ?
!d discord.Member.add_roles @rapid knoll
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to
use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list
of roles than the highest role of the member.
i wll check
i dont think so
May just be a bug with nextcord then
Usually that specific error happens with an incorrect bot token
should i make a variable for it and regenerate the token
Good idea
A Python wrapper for the Discord API forked from discord.py
this one?
ah shit no
..
1.8 something
XD
let me check again what do i type in the terminal to check version again (vs code terminal)
pip show nextcord
Code:
`import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=">")
@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")`
Error:
Traceback (most recent call last): File "d:\Kunnu\Discord.py\LF Test\bot.py", line 7, in <module> @bot.slash_command() AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
u need to install from github
hmm ok
i get this ```pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- pip show nextcord
-
+ CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException```
pip install git+https://github.com/Rapptz/discord.py.git
rip
python -m pip....
im using pycord...cos discord.py doesnt have slash commands
it does
giving bots permissions is it at:get_permissions() at = @
ok the version is correct i am a idiot
can u tell me how to make slash commands in discd.py ?
my version is correct
then what is wrong
python -m pip
Try @client.slash_command
gives this error:
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
ya its called app_command in discord.py
im using nextcor
what does RuntimeWarning: Enable tracemalloc to get the object allocation traceback mean
d
@tropic burrow
...
Look at his error
ill resend everything jere
show the error b4 that, u need to enable some env variable to view that which is not really necessary
He doesn't have one
oh
import nextcord
from nextcord import Interaction
from nextcord.ext import commands
testingServerId = N/A
intents = nextcord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "!", intents=intents)
@client.event
async def on_ready():
print("The bot is now ready to be used")
@nextcord.slash_command(name = "hello", description="Replies with hello")
async def hellocommand(interaction: Interaction):
await interaction.response.send_message("Hello")
client.run('N/A')```
Error: Runtime Error: Event loop is closed
Bruh
that's not an error, it's a warning
but nothing prints
show the error above that warning
the traceback?
Yes
!paste if big
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
#bot-commands @rapid knoll
File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed```
my user will be censored
How can my bot see when someone upvoted on discordbots.com?
And then start a 12 Hour timer?
ok so i have this code to uh set log channels for different servers
def setlogchannel(bot, message):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
logchannels[str(ctx.guild.id)] = logchannel
with open('logchannel.json', 'w') as f:
json.dump(logchannels, f)
await ctx.send(f"Changed the logchannel to {logchannel}")```
and when i set it in a event :
```@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"deleted message!")
embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
logchanneld = bot.get_channel(int(logchannel))
await logchanneld.send(embed=embed)```
the issue is i can not call it in the event
logchannel
and i cant use it as a global variable because it's set as a parameter under the def function already
What is the best date/time package in Python?
humanize?
I'd say datetime
Pendulum is nice also
But still datetime is easy to use and it's in the standard lib
Lol
Haha was just wondering if there are any others worth knowing, thanks all 🙂
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
vouch
please tell me which discord bot to use for the host, telegram bot?
so i tried something else
import discord
TOKEN = "[REDACTED]"
client = discord.client()
@client.event
async def on_ready():
print("{0.user} is online1".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith("!hello") or message.content.startswith("/hello"):
await message.channel.send("Hello Pyramid Finder!")
client.run(TOKEN)
error is client = discord.client() TypeError: 'module' object is not callable
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
def setlogchannel(bot, message):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
logchannels[str(ctx.guild.id)] = logchannel
with open('logchannel.json', 'w') as f:
json.dump(logchannels, f)
await ctx.send(f"Changed the logchannel to {logchannel}")```
and when i set it in a event :
```py
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"deleted message!")
embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
logchanneld = bot.get_channel(int(logchannel))
await logchanneld.send(embed=embed)```
my issue is : await logchannel.send(embed = embed)
NameError: name 'logchannel' is not defined
any more sweet questions?
logchanneld = bot.get_channel(int(logchannel)) where have u defined logchannel??
buut it's under a async def so that's what im trying to figure out
where do u want to send the deleted message in?
a log channel that is set in a shit json database?
uwu?
dude the thing is im designing this to be a example of a public bot with log channel database so that i don't have to set a actual id everytime someone sets a log channel
wait no ew
when someone sets a log channel, that id goes to the json file right.... so whats the problem?
yes but it tells me that logchannel is not defined and i pretty much need the idea of how i can define it that it works
is there an event for when a command is ran?
what channel do u want it to send message in if its not defined?
no the thing is i set logchannel as the id it sends to the json file and im trying to use it as a parameter for the channel that the log is going to be sent to however it seems it doesn't work
yeah, on_command
You never defined logchannel in the on_message_delete event m8
and could u help me how can i exactly define it because that's what i've been trying to find since morning
example of what u can do
{<guild_id>:
{"log_channel_id": 128372913} // lets say this is the default id
}
@bot.command()
async def setthelogchannel(ctx, logchannel):
with open('logchannel.json', 'r') as f:
logchannels = json.load(f)
logchannels[ctx.guild.id]['log_channel_id'] = logchannel
with open('logchannel.json', 'w') as f:
json.dump(logchannels, f)
...
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = None):
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
await ctx.send("Укажите причину")
return
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print(1)
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,reason))
base.commit()
print(2)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
print(3)
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
If a person has no warnings, then when you give out, the bot does not write anything to the chat, but he issued a warning, if you issue it again, the bot will already write, how to fix it?
for the first part there's technically no default log channel id
then.... where r u gonna send the message?
ignore that for now, ur code has errors
🤷♂️
ok just few issues fixed
but u still did not actually fix the main issue, logchannel is not defined under on_delete event
well because... ur not taking the id from the json
ur just storing it and not using it? why?
import discord
import os
import requests
import json
TOKEN = "N/A"
client = discord.Client()
def get_joke():
response = requests.get
("https://api.icndb.com/random")
json_data = json.loads(response.text)
joke = json_data[0]['q'] + " -" + json_data[0]['a']
return joke
@client.event
async def on_ready():
print("{0.user} is online1".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith("!hello") or message.content.startswith("/hello"):
await message.channel.send("Hello Pyramid Finder!")
elif message.content.startswith("/joke") or message.content.startswith("?joke"):
joke = get_joke()
await message.channel.send(joke)
client.run(TOKEN)```
So no jokes happen why?
are u trying to run a bot or selfbot
bot
change client to bot
import discord
import os
import requests
from discord.ext import commands
import json
TOKEN = "N/A"
bot = commands.Bot(command_prefix= "your prefix")
def get_joke():
response = requests.get
("https://api.icndb.com/random")
json_data = json.loads(response.text)
joke = json_data[0]['q'] + " -" + json_data[0]['a']
return joke
@bot.event
async def on_ready():
print(f"{0.user} is online1".format(bot))
@bot.event
async def on_message(message):
if message.author == bot.user:
return
elif message.content.startswith("!hello") or message.content.startswith("/hello"):
await message.channel.send("Hello Pyramid Finder!")
elif message.content.startswith("/joke") or message.content.startswith("?joke"):
joke = get_joke()
await message.channel.send(joke)
bot.run(TOKEN)```
Can anyone write me code that will make me more patient waiting for top.gg to approve my bot 
if i'm not wrong this isn't a slash command format
oh.. the respons.text
while not_approved:
wait()
You can just send it as a regular message
Get the channel, send it
Just like regular
As if this was a regular non slash command
Yea, but you always need to reply to the interaction, else it will say that the interaction failed.
You can defer it
Well you still won't reply
Defer only gives you more time to reply if i'm correct, but if you send a message in the channel instead of replying then it's useless
This isn’t even right
Bot isn’t part of the discord namespace
It’s inside ext.commands
You changed the variable to Bot but didn’t event change everywhere where it’s supposed to be referenced
I mean, it would say that the application did not respond
this is horrible
I can't say it any nicer
As far as discord cares if you defer you've responded
How to make a check so that bots, in principle, cannot be added to the black list, in the screenshot, only the bot executing the command cannot be added to the black list
elif member.bot?
Oh, didn't know that.
member.bot is true if the member is a bot account
thanks you so much
it's not mine as well
I saw the client code before and it was much better
Yep it was
all i did was replace client with bot
because according to my small brain client does not work for bots
- you didn't replace it everywhere
- a Bot instance is coming from discord.ext.commands and requires a command_prefix kwarg passed to it
- you didn't follow pep8 while making the Bot instance and capitalized it
- you did want to replace the Client instance with a Bot instance and tried to do so, but didn't use the pros of having a bot and continued to work with on_message, still using more memory because of the Bot instance
you could've also told him to use aiohttp instead of requests
bro is gonna kill me on my second day on discord.py
👍🏿
i'll try fixing it if u want anyways
python doesn't care if you follow pep8 or not
k but I do and it's good practice 😔
sure, and it always is
Best to learn best practices
ok check now hope its better
I'm starting to like it, you made a slight mistake in on_ready and on_message
because you used Bot instead of bot which is undefined
ok fixed
Why when I put the bot on the hosting, it is displayed as None and how to make it so that my nickname and ID are displayed?

i'll keep wondering until i sleep what i did wrong
maybe i just have low iq for python lol
maybe tell me whats wrong so i can get some more info
thats his code
, ik there's some shit there but i honestly just bothered fixing the main issue that his bot doesn't respond or something like that
thats the problem with python discord bot APIs tbh. Being something that is seemingly a fun project for a beginner and being in a language like python that targets all experience levels of the programming world you can get quite a large divide is the abilities of the users and hence APIs like discord.py and it's derivatives are very sophisticated however they really expect you to know python and it's intricacies. Something you will see a lot is beginners writing all of these subclasses and using all of these decorators without ever learning how or why they work, or why we need to put await before some functions and the idea of blocking
tl;dr if you are new to python and are finding discord bots hard don't worry about it, they can be hard
Prolly worth mentioning that bots are actually not that difficult to write, you can do on message and all that stuff and it'll pretty much work perfectly fine
it's a good starter project if you actually try to find out why and how those things you write work, otherwise you just write stuff, but never get to a higher level of doing more and more advanced projects
or being able to
@tropic burrow
response = requests.get("https://api.icndb.com/random")
json_data = json.loads(response.text)
joke = json_data[0]['q'] + " -" + json_data[0]['a']
return joke```
```py
@bot.command()
async def joke(ctx):
await ctx.send(get_joke())
kind of better
discord.Member.bot
i just like how none of our codes work xd , it's his issue probably so 
or api dead
I think that second option is a bit unrealistic
might it be in his get_joke?
!d json.loads
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *s* (a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray")
instance containing a JSON document) to a Python object using this
[conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
The other arguments have the same meaning as in [`load()`](https://docs.python.org/3/library/json.html#json.load "json.load").
If the data being deserialized is not a valid JSON document, a
[`JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError "json.JSONDecodeError") will be raised...
dunno
hello
because hes a meanie😡
@heady sluice
import aiohttp
@bot.command()
async def joke(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://api.icndb.com/random')
jokejson = await request.json()
await ctx.send(jokejson)```
his api is just dead
wdym and the code can be shorter
well yeah but i used a aiohttp method as well which works but for some reason the command does not respond with his api
wdym it doesnt respond
did you check the status code if any?
yep his api is bad
bro
youre trying to view the endpoint
with your browser
boolean? oh I know what that is
How would discord.ext.tasks work with multiple bot instances? If i'm not mistaken there's nothing synchronizing these
you don't use multiple bot instances
Why not?
you can only run one too
tell me one reason to
Ehm, why we have auto sharded bot then? 🙂
I see, how do you scale it past single physical node then?
please rephrase
If you run into some kind of bottleneck how would you scale past one server (physical server where you run your bot)
I probably won't run into such problems but i'm still curious how would you do that 🤔
what
I don't know
this
I see
Hello
hi
It's not really related to tasks, just trying to figure out how would you scale your bot past single process or server (not discord server)
we're bottlenecking server past one, you haven't worked with tasks yet so we're all numb
so hosting?
or just the process of scaling your bots into servers?
Yep, or just having multiple processes running on same host
ah well you may ask here #965291480992321536
It's not related to hosting 🤔
Same bot, multiple instances/processes
you mean shards😭
yeah shards run on one process
im so confused😭
AutoShardedBot just acquires more connections, if you run into some kind of cpu bottleneck you'd need more processes
ah well im not quite familiar with multi processing 🏂
Doctor you're asking two people dumber than u
but using shards on more processes are even weird to think about
Everybody is a Genius. But If You Judge a Fish by Its Ability to Climb a Tree, It Will Live Its Whole Life Believing that It is Stupid -Albert Einstein 🧍
which process would handle which shard
and which all of them
Robin
I don’t know. I have a fishy friend who can climb a tree just fine
whos that fishy friend
well that's not what I was counting on when I saw Robin typing
maybe ill eat him😋
I guess you can manually setup shard ids for each bot instance
😔
Unfriended
do you run Carl
I think you're fine unless you do
Ehm, no 😅 just curious on how would you do that
i dont need you because i already have hunter😡 😤
Nothing wrong with wanting to know
he can remove all viruses from your computer
Heck I’ve wanted to do my own autoshardedbot just because
Never gotten around to doing it tbh
yeah because hun hun is indian
😩
the secret cheat code
yuppppp
gfu.....
u need to put f before the string like f'...'
ya
ty
File "c:\Users\Yuki\Desktop\KyuuMainPy\discord-music\main.py", line 63, in <module>
bot = MusicBot(command_prefix=PREFIX, intents=intents)
File "c:\Users\Yuki\Desktop\KyuuMainPy\discord-music\main.py", line 27, in __init__
self.loop.create_task(self.start_nodes())
File "C:\Python310\lib\site-packages\discord\client.py", line 110, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000180AB95B9D0>``` dpy 2.0
import os
import wavelink
from discord.ext import commands
from discord import Intents
from essentials.player import WebPlayer
from dotenv import load_dotenv
import pathlib
import sys
load_dotenv(".env")
os.environ["JISHAKU_NO_DM_TRACEBACK"] = "true"
class MusicBot(commands.AutoShardedBot):
def __init__(self, command_prefix, **options):
super().__init__(command_prefix, **options)
self.can_function = False
self.error_message = (
"Bot is not ready to listen your commands. Please try after a few moments."
)
if not hasattr(self, "wavelink"):
self.wavelink = wavelink.Client(bot=self)
self.loop.create_task(self.start_nodes())
async def on_message(self, message):
await self.process_commands(message)
async def on_ready(self):
print(f"{self.user} is ready to play musics")
async def start_nodes(self):
await self.wait_until_ready()
await self.wavelink.initiate_node(
host="",
port=,
rest_uri="",
password="",
identifier="",
region="",
)
for guild in self.guilds:
if guild.me.voice:
player: WebPlayer = self.wavelink.get_player(guild.id, cls=WebPlayer)
try:
await player.connect(guild.me.voice.channel.id)
print(f"Connected to existing voice -> {guild.me.voice.channel.id}")
except Exception as e:
print(e)
self.can_function = True
intents = Intents.default()
intents.members = True
PREFIX = os.getenv("PREFIX")
bot = MusicBot(command_prefix=PREFIX, intents=intents)
@bot.event
async def setup_hook():
for file in sorted(pathlib.Path("cogs").glob("**/[!_]*.py")):
ext = ".".join(file.parts).removesuffix(".py")
try:
await bot.load_extension(ext)
except Exception:
print(f"Failed to load extension: {ext}", file=sys.stderr)
@bot.command()
@commands.is_owner()
async def reload(ctx, extension):
await bot.unload_extension(f'cogs.{extension}')
await ctx.send(f"unloaded {extension}")
await bot.load_extension(f'cogs.{extension}')
await ctx.send(f"loaded {extension}")
@bot.command()
@commands.is_owner()
async def unload(ctx, extension):
await bot.unload_extension(f'cogs.{extension}')
await ctx.send(f"unloaded {extension}")
@bot.command()
@commands.is_owner()
async def load(ctx, extension):
await bot.load_extension(f'cogs.{extension}')
await ctx.send(f"loaded {extension}")
TOKEN = os.getenv("TOKEN")
bot.run(TOKEN)```
setup is now async in dpy 2.0
https://gist.github.com/Rapptz/6706e1c8f23ac27c98cee4dd985c8120
check this out
how would these both go in the same if statement
Yeah it was a breaking change a bit ago
if endswith('all') and endswith('max')
It can’t
thx 😄
But where is it erroring im a bit confused
How would it endwith both?
oh right, im fucking dumb
you’re looking for the or operator
Nah, you’re thinking quantum!
the thing is stuff like bot.run and other stuff are async, so u need to make an async function, put that there and run it using asyncio.run, check the gist i sent, it has examples to help you
ok, could i make it so if i have a command test for example, and i wanna make it so if they do .test max or .test all it would send the same response how would i do that in one if statement
are you using on_message?
no
So that’s an or operator
But you should probably do this with a command
@client.command
As I'm trying to get my bot token, it just says "Reset Token." Can anyone help out.
u will have to reset it then
@client.command()
async def test(ctx, arg):
if arg in ('max', 'all'):
...
to generate a new one since it gets hidden after time
ok cool
and i can do if arg==None then my regular command
Yeah I do, I click reset
They made it so you can only see it once
and my 2fa code is apparently invalid.
like what.
Do we need to keep the -
or no?
The what?
Yes?
mk.
You should have a 2fa app on your phone
What...
Either that or use your backup codes
What's the app called?
I use google Authenticator
mk.
If you lost your backup codes that’s a big issue
What..
toss away ToS
!bot-var
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
this
whats kor? AM?
you attach a variable to your bot so you can change it everywhere
even in other files
where's that
ur time thing
oh it's the ending
yeah Hungarian makes the words have other meanings with every single ending possible
0.o
ah cool
@commands.command()
async def imagify(ctx, url: Union[discord.Member, str], size: int = 14):
if not isinstance(url, str):
url = url.display_avatar.url
def get_emojified_image():
r = requests.get(url, stream=True)
image = Image.open(r.raw).convert("RGB")
res = emojify_image(image, size)
if size > 14:
res = f"```{res}```"
return res
result = bot.loop.run_in_executor(None, get_emojified_image)
await ctx.send(result)
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 919, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: 'await' outside async function (image.py, line 40)
discord messed it up
ur awating in get_emojified_image which is a sync function
how can I make data from one command be transferred to another ??
how to create this variable?
bot.variable = ...
you can create it anywhere and it's like any other variable
you just attach it to bot
like Ryuga
how did this get to await ctx.send() after the return
please code
you used stat before you assigned anything to it
maybe self.bot.variable = message?
@heady sluice and now in order for me to transfer this variable to another command, I need to write "self.bot.variable = stat" or just "stats"
it doesn't matter what you set to it
@commands.command(aliases = ['status', 'Status', 'статус', 'Статус'])
@commands.has_permissions(administrator = True)
async def __stats__(self, ctx, *, message):
stat = message
self.bot.variable = stat
embed = discord.Embed(description= f'Вы установили статус {stat}', colour=0xF1C40F)
await ctx.send(embed=embed)
```you could use this
or spare yourself a variable
@commands.command(aliases = ['status', 'Status', 'статус', 'Статус'])
@commands.has_permissions(administrator = True)
async def __stats__(self, ctx, *, stat):
self.bot.variable = stat
embed = discord.Embed(description= f'Вы установили статус {stat}', colour=0xF1C40F)
await ctx.send(embed=embed)
it doesn't work out the variable is (message) and not (stats)
I'm trying to run this simple bot:
from discord.ext import commands
from secret import Secret
client = commands.Bot(command_prefix='.')
@client.event
async def on_ready():
print("Bot is Ready.")
#
# @client.event
# async def on_member_join(member):
# print(f'{member} has joined.')
#
#
# @client.event
# async def on_member_remove(member):
# print(f'{member} has left a server.')
@client.command()
async def add(ctx, num1: int, num2: int):
await ctx.reply(num1+num2)
client.run(Secret.bot_token)
My bot shows up in discord channel, but I couldn't run the /add command or it's not in the command list.
yes, it doesn't matter what's after the =
it will be transferred and as I see, stat = message
you do you
when I stop I would get this:
add is a command that you invoke with .
could someone help me debug?
you type .add in the channel
oh not slash
I tried this: Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "add(3,4)" is not found
you use it like
.add 3 4
oh
i use discord.py
let me check
discord.py 1.7.3
the slash command is pretty nice, do you know which repo/library I can use for slash command?
all of the dpy forks include slash commands I think
and dpy 2.0 too
you can use self.bot.variable in another command
thanks, I'll look into that 😄
popular forks:
disnake, pycord, nextcord
so I created in command A 'self.bot.variable = stat' and what exactly should I transfer to command B ??
that's for your help 🙂
you can do anything with it, easiest to try is
@commands.command()
async def command_b(self, ctx):
await ctx.send(self.bot.variable)
use disnake
did you use the other command beforehand?
do pip install disnake
without restarting the bot?
then control h
force not
replace discord with disnake
??
i saw that
@sick birch help
I asked if you used command A which sets self.bot.variable before command B
what seems to be the issue
ah just saw it
Full traceback?
I suspect that's not where the error is pointing
wait are you making an avatar command
Command raised an exception: AttributeError: 'Bot' object has no attribute 'variable'
The full traceback
1.7 moment
That still doesn't look like the full traceback, there has to be something above
AttributeError: 'Bot' object has no attribute 'variable'
its a profile c9mmand right
Unless you have a shoddy error handler that's messing with it
don't go off topic
They don't want you derailing the conversation I'm guessing
I'll ignore that
could it be because command status is lower than command prof??
did you use command A before command B?
takes a while to edit oh phone ;)
I can't diagnose the error without the FULL traceback, seems like you chopped off a part of it
no
well that's the only way it works
or you set self.bot.variable outside of a command
but I doubt you'd want to do that
so first use command A then command B
that is, do I need to set command status higher than commands prof ??
@heady sluice has
I swapped them and everything works

@heady sluice I'm in ahuya myself
can some1 explain me, why my slash command isnt loaded in my server. I use guild_id and when I run the bot, no errors occur
how do you sync it
that's dpy indeed 
Don't see that often these days
he's a man of culture
I like the design pattern when it came to sync
smth like this line?
await bot.tree.sync(guild=discord.Object(id=935587959095320676))
oh wait
it's
await tree.sync(guild=discord.Object(id=guild_id))
there
this is one thing I'd dare put in on_ready
it would accidentally keep my stuff up-to-date
exploit bugs
You could still argue it's bad on the grounds that sending an API request on_ready is going to get you kicked off the API
and making a task for the exact same thing would be much more practical
Right, but if you don't really care about syncing it on an interval, setup_hook() works just fine too
never used it
@heady sluice stop, you can also make the team work even if one of the teams was not used
@heady sluice
until you write the status command in the prof command, it is written to you that the status is "missing"
exactly!
ah ye, completely forgot that to add
and if you restart the bot it will be undefined again
if you would want to store it somewhere then
well... depends, is this something for every user? then I would get a database ||or json||
well, I need it so that if it is indefinite, the command will still work and say that it is not there
@commands.cooldown(1, 60, commands.BucketType.user)
@work.error
async def work_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"**Wait a little bit lmao**",description=f"Try again in `{error.retry_after:.0f}` seconds.", color=discord.Colour.red())
await ctx.send(embed=em)```
How would i put the cooldown time in minutes?
if self.bot.variable:
#the variable exists
else:
#it doesn't exist
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount
of times in a specific time frame. These cooldowns can be based
either on a per-guild, per-channel, per-user, per-role or global basis.
Denoted by the third argument of `type` which must be of enum
type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType")...
mmm
1*60
it's actually the only way to put it in seconds, so
x*60 where x are the minutes would work
yeah but in the error message
how would i make the error message display minutes instead of seconds
Invalid format specifier
if self.bot.variable:
ctx.send(self.bot.variable)
else:
ctx.send('Отсутствует')```
the what
!e print(465.5:.0f/60)
@heady sluice :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(465.5:.0f/60)
003 | ^
004 | SyntaxError: invalid decimal literal
I don't even know how what you did works
i get that a lot
!e print(int(465.5)/60)
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
7.75
description=f"Try again in `{int(error.retry_after)/60}` minutes."
got it like that now but still not working. am I missing something ? https://i.gyazo.com/b9c54a9fe719c95d1d2fff2df91f1682.png
how did this become so different so quickly
I think you should put new_command_onygo inside the Bot class
I use "class Bot" in one of my other bots with @pearl wigeon.comand and it works so I pasted it. or at least it worked but should work. let me check
description=f"Try again in `{int(error.retry_after/60)}` minutes." seems much nicer
andy
hello
I would suggest a ternary here so you don't get a long floating point number
but int doesn't round
it just cuts off the decimals
ah thanks 😄
so int(9.9999999) is equal to 9
So then it would say, Try again in 0 minutes. in some cases
!e ```py
print(int(1/60))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
0
!e
print(int(1/60) + 1)
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
1
But the actual cooldown isn't a minute...


dont get it how
try again in less than int(1/60) + 1 minute(s)
if retry_after % 60 == 0:
return retry_after / 60
return round(retry_after)
``` would be what you want
Not doing all this int stuff that would show you the wrong time
round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
!e ```py
retry_after = 120
if retry_after % 60 == 0:
print(f"retry in {retry_after / 60} mins")
else:
print(f"retry in {round(retry_after)} seconds")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
retry in 2.0 mins
!e ```py
retry_after = 100
if retry_after % 60 == 0:
print(f"retry in {retry_after / 60} mins")
else:
print(f"retry in {retry_after} seconds")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
retry in 100 seconds
You can call round on retry_after / 60 for a cleaner number
modulo operator will check if there is a remainder, in case you were wondering
.
Lets say ur creating a bot to return stock info, if u do the the command !stockdata TSLA, it should return the data
Or u do !stockdata
The bot will ask u for what stock and u input the ticker symbol
That sounds like a perfect way to use wait_for
any videos for this kinda thing
Can we talk in dms
Why?
Just a normal question, I host my bot on my PC with Pycharm, will it go offline if I put my pc on Sleep Mode?
Well i'm gonna try it and see thanks!
got it like that now but still not working. am I missing something ? https://i.gyazo.com/b9c54a9fe719c95d1d2fff2df91f1682.png
What's copy_global_to?
what are u talm bout
about youtube Terms of Service
its not youtube?
I wanted to go to bed now I'm back here 
Where's the audio from?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
its not ytdl
it's wavelink
copy_global_to that can copy a globally defined application command to a guild logically. prolly unnecessary
behave
Better safe than sorry
mhm
Please keep it civil, we don't appreciate you insulting other members
im not insulting im just stating facts
but dosent change somth. still not working
How can I make my bot do this for each message sent? ```py
q = str(ctx.message.content)
answer = requests.get(f'{API}{q}')
print(answer.json()['cnt'])```because ```py
@client.command()
async def on_message(ctx):
q = str(ctx.message.content)
answer = requests.get(f'{API}{q}')
print(answer.json()['cnt'])``` doesn't work, it just leaved the console without anything.
alot of people in this server think they are the discord sheriff
Not necessarily. None of us want to get banned
listen, you do you, but we don't help with projects that break any Terms of Services
i didnt say anything and mister broom up his arse denial cringe dude comes playing sheriff
when
<@&831776746206265384>
cringe
look at ur name @slate swan
i mean, you’re free to do as you wish in dms
its just not allowed here
i dont listen to non mods
cuz reasons
it indeed isn't
so i dont care
im not telling you to do anything ;-;
Please stop insulting other members
does someone really have to be a mod to point someone to the rules
"demon" 💀
mister denial come into my dms rq
me?
can we maybe change the subject and help me 
everything in dms stays in dms apparantly
...?
no what i meant was
for example, when i first learnt python i made a discord selfbot
just for fun
stop
but im not gonna ask people for help with that here
Please respect other members. We won't help or encourage use of code that breaches terms of service, as you have been told.
thank you
different servers have their own rules
you might find a server where you can talk about tos breaking stuff
where does anything say about ytdl
but that isnt here
Spirit of the law over letter of the law
💀
what nig
profound
the youtube ToS doesn't state ytdl, it states the general download of audio from youtube
I'm assuming you saw that Grote?
ytdl is just an example of a library that uses copyrighted music without a license, using wavelink to do it instead doesn't make it okay.
oh
ok and where does my code prooves it downloads anything?
Hey there!
Any ideas how i could fix this issue where the embed size changes massively depending on how long the name of the seller is?
so me downloading videos for my soundboard was a no no 💀
Exactly, we want to err on the side of safety when we're not sure of your intentions

inline = False
was it automatic
from like a bot
nah
okay and why are you "warning" me for doing nothing wrong??
Legend, thank you very much!
i just wanted a spike defuse sound for some valorant trolling
np :)
That would be a violation of copyright in pretty much every country if you play that sound board to people
oof
Listen, I have no quarrel with you. Just don't continue this as we do not want to assist you with projects that may be in violation of discord's terms of service
help please
with?
the package used is speedtest-cli(it is the only package we need)
import speedtest
from time import sleep
speed=speedtest.Speedtest()
option=int(input('''
What do you want to know:
- Download speed
- Upload speed
- Both Download and Upload
- Ping
Your choice: '''))
if option<1 or option>4:
sleep(2)
print('You have entered wrong choice, please enter again with values from 1 to 4')
else:
sleep(1)
print()
print('Pls wait, test in progress...')
print()
down_speed=round(speed.download()/1000000,3)
up_speed=round(speed.upload()/1000000,3)
print('One more sec please...')
sleep(2.5)
print()
if option == 1:
print('Your Download speed is: ',down_speed,'Mbps')
elif option == 2:
print('Your Upload speed is: ',up_speed,'Mbps')
elif option == 3:
print('Your Download speed is: ',down_speed,'Mbps',end=" ")
print(',and your Upload speed is: ',up_speed,'Mbps')
elif option == 4:
s=[]
speed.get_servers(s)
print(speed.results.ping,'ms')
else:
print('Sorry, something went wrong, pls try again...')
u do have quarrel with me, i did not ask for help with ytdl anyways and the code i did ask for help doesnt state any use of ytdl plus my issue was not with ytdl so stop having a "quarrel" with me (||in my words a broom up your arse||)
This is a channel specifically for discord bots, check out #❓|how-to-get-help for information on opening a generic help channel
Try speed=speedtest.SpeedTest()
Wavelink is a way of streaming music no. I doubt you have a license to stream music to others, so that would be against the ToS of every source of that music. A common source is YouTube, hence the ytdl embed.
but where do you have proof im using ytdl i am literally not
And we don't help with projects that involve things that break tos, even if the problem isn't in that part.
It's not about ytdl, it's about streaming music
I never said you were. I am saying wavelink is the issue.
what if im using a opensource api that uses uncopyrighted music
the youtube ToS doesn't state ytdl, it states the general download of audio from youtube
hmm
it's the same thing
u have a quarell with me ||who shit u in ur brain in my words|| when did i say im using youtube?????
making up stuff cuz u have a quarell with me
can a mod just end this
"quarell"
well
dm pls
ok
That's great, however we can't confirm your intentions. And like I mentioned, we want to err on the side of safety
i hate fetch methods



