#discord-bots
1 messages Β· Page 586 of 1
@slate swan bot.event doesnt have ()
okay same
Move inside async but not inside if
doesnt work
@slate swan can u show me more code
I mean show me full on_message code
And plz use
!paste
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.
how
Blindly ctrl c and ctrl v
U need process_command line
Delete all of that extra space
so I'm trying to get my bot to join the voice chat I'm in when i run a command
here's what i have
@bot.command("join")
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()```
but it just doesn't join, does anyone know what I'm doing wrong?
i am using bot.event ?
so why does it not work
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
@slate swan delete it until the colon and just press enter
where?
like this?
Try it and see
Indent it
nope same
indent what and how
voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='General')
Please learn basic python before jumping in to dpy its not the best thing to do
yeah but it doesnt sadly
Have u saved your file
yess
Can I see your full code?
How can I change this is to if a member in voice channel, join it?
!paste
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.
!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.
Like this
tell me pls!
@bot.command("join")
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()```
does anyone know why my bot isn't joining the VC I'm in when i run the command?
I think this is outdated
Your on_ready working?
how can i check if a user is streaming/watching/viewing/listening to, ect
If yes then can u check what your discord.py version is
yes shows me in console
pls tell me!!!!!!!!!!!!!!!!!!
i just found out that must be the cause as my discord.py was clashing with nextcord
now i removed both
I don't think it might be issue
do u know what the not outdated way of doing it is?
no
@slate swan frsh install and try then
I dont think you need capital i
Huh
!d discord.Intents you need a capital i
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
what version of discord are you using?
u mean discord.py?
or discord client
what else am I talking about then
how do i check
!d discord.version
discord.__version__```
A string representation of the version. e.g. `'1.0.0rc1'`. This is based off of [**PEP 440**](https://www.python.org/dev/peps/pep-0440).
Print that
Did you imported intents?
like that?
yes
You do
I always import it tho
error
AttributeError: module 'discord' has no attribute 'version'
How to make button disabled in nextcord?
Yeah i know i got corrected already
it isnt
This
I always thought it was
AttributeError: module 'discord' has no attribute 'version'
wtf
rip
What in tarnation
What
Pip install discord.py
Is discord.py even installed in your pc?
can you show me the discord.__version__ part
what does it print
hm
pip install --upgrade discord.py try doing this
voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='General') how to change this to if member in voice channel join it
hi i need help with an embed sayin user has been banned
and user replaced with the user that has been banneed
huh
in one line
use the member object
same with pip3
What
ye but like
U know how to make embed mateπ
the code with description
sorry for trying to learn embeds mb
like what
It's ok glad u told the truth π
just in one line cus ive tried
Why would you want it all on 1 line?
!d discord.Member Like I said earlier
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
just looks better
i made it on 2 different lines
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
or i just want the tag and the sentence
How many python version u have in your system mate?
not the code sadly
just one
Yeh try it
Like I said use the member object
example?
π
@slate swan remove and in console do pip show discord.py
member.?
U want to change what in embed
member is already a member object if you typehinted that to discord.Member use that oml
hm
π₯²
to make tag and sentence in one line
Try asking in dpy server
like what do i add between them
@robust ridge dude
dpy?
ok ok calm down lol
@slate swan now try the code and remove that print statement
Tag? Which tag
user tag
mention i dont mind
@slate swan try asking here
member.mention
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
when i add a new field or just on the same line as embed= etc
I already gave you an example
like the name and description
read pls
Where ever you want
What do you want to achieve?
nonono
ok so how do i add it in one line without getting error
cus it will be in different lines
if i use description and name
or title etc
What do you wanna add?
just to make it in one line...
intents = discord.Intents().all()
Oh
Try this
If iirc(f"{member.mention}")
TY
Make an embed in one line is that what you mean?
use 2.0?
how
ye but lemme try what @slate swan gave me
Only field has option to print side to side
o
@robust ridge Bro
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (in this case ZeroDivisionError)
β’ Make note of the line number (in this case 2), and navigate there in your program.
β’ Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
I dont really know what he wants but im glad to help
it was pretty clear he isnt using 2.0 no need for a traceback
install it from master branch
Traceback give very clean idea what might be messing up
where?
github
can u link
it does, but it isnt needed in this case
google exists for a reason
so i uninstall discord current version?
before installing it
I guess idrk
i got the bot to work fixed the indentation thanks for the help and @mild token you too
Yw
what's Yw?
Your welcome
@slate swan this is how you would do it for repl.it, but depending on what your setup is, some of these steps may help: https://pythonrepo.com/repo/Pranav-Saxena-Guide-To-Install-Discord-Py-Master-Branch-on-Replit
I do not know why it is not added outputs an error I will attach an image of the base
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "O:\Suzuki\cogs\settings.py", line 186, in on_member_join
await member.add_roles(auto_role)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\member.py", line 898, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'Int64' object has no attribute 'id'
code
@commands.Cog.listener()
async def on_member_join(self, member):
auto_role = self.collection.find_one({"_id": _id})["auto_role"]
if auto_role == None:
pass
else:
await member.add_roles(auto_role)
get_role(role_id, /)```
Returns a role with the given ID.
if I wanted to convert this to the format you would use for cogs, then what would it look like in the cog?
class Dropdown(discord.ui.Select):
I keep getting errors using the fields in the Select struct and not sure how to properly call it. I have the source code up for Select and verified i have the variable names correctly spelled. Still a noob here and kinda lost.
command.Cogs
so
auto_role = guild.get_role(auto_role)
await member.add_roles(auto_role)
mhm
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 104, in help
embed = discord.embed(
AttributeError: module 'discord' has no attribute 'embed'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/aarav/Library/Python/3.8/lib/python/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: module 'discord' has no attribute 'embed'```
discord.Embed ^^
It's discord.Embed
.
import discord
from discord.ext import commands
class Menu(commands.Cog): # Category type is the class
def __init__(self, bot): # using self bc using class
self.bot = bot
@commands.command(brief="Provides a menu of all Bot commands")
async def menu(self, ctx):
await ctx.send(
content = 'Select an option:',
#discord.placeholder('Please select an option.'),
options = [
discord.SelectOption(label='Option 1', description='This is option 1', value='1'),
discord.SelectOption(label='Option 2', value='2'),
discord.SelectOption(label='Option 3', value='3'),
discord.SelectOption(label='Cancel', value='Cancel'),
],
custom_id='MainMenu'
)
interaction = await self.bot.wait_for('select_option', check=lambda inter: inter.custom_id == 'MainMenu' and inter.user == ctx.author)
res=interaction.values[0]
if res == 'Cancel':
await interaction.send('You have canceled your select option')
else:
await interaction.send('You have selected %s option' % (res.label))
def setup(bot):
bot.add_cog(Menu(bot))
commands.Cog or command.Cog idk which one
Cog is from the commands extension
the error gets stuck with placeholder and options
@bot.command("join_v")
async def join_v(ctx):
connected = ctx.author.voice
if connected:
await connected.channel.connect()```
does anyone know why my bot won't join the voice channel
the current code compiles. when i run it, i get this error: Command raised an exception: TypeError: send() got an unexpected keyword argument 'options'
@bot.command(name="join_v")
i tried discord.options, discord.ui.Select.options
none of my other cmds have that though and they work
neither worked. self.options didn't work either
try using the jsk extension
aka jishaku
bot.load_extension("jishaku")
<prefix>jsk dbg <command>
.
It gave me an error
NameError: name 'bot' is not defined
not sure what i did lolll
put it under your
bot = commands.Bot
discord.ext.commands.errors.ExtensionNotFound: Extension 'jishaku' could not be loaded
Npπ
does discord.py have buttons yet?
?
master branch yes
def get_dog():
url = " https://api.thedogapi.com/v1/images/search"
querystring = {"min":"10","max":"20","fragment":"true","json":"true"}
headers = {
'x-api-key': "------"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data=json.loads(response.text)
return(dog)
@client.command()
async def dog(ctx):
dog=get_dog()
await ctx.channel.send(dog)
i want it to return an image
but its giving back the word 'dog'
could i be using an outdated version of discord.py or something?
What dpy version are you using
Yes, only onthe master branch
Anyone knows how to setup lavalink/wavelink in heroku?
Bruh
dog isnt defined in the function?
return(dog)
oops, i had my phone ontop of my keyboard
yeah so how do i define it?
how would I know..?
ummmmmmm thats a really good question
1.16.0 i think
bruh
so outdated
i forgot about the bot for a while
Well
jsk at least requires discord.py 1.7.3 and above
wont work on earlier versions on dpy
is mongodb safe
yes
people say its easy to hack :/
so i figured out variable shadowing is causing this issue with my bot
and yes i installed 2.0
but which one do i rename /remove now
π₯²
If you are bad at making a good password, and bad at keeping your URL a secret, then yes.
wait im using the most recent version of discord.py i think so idk why jsk is giving error
i use the "generate a secure password" thing
so its random letters (but ofc i do note it donw)
hello people
@boreal ravine hello again!
im here rdy to learn another challenge that ive set myself against
how can i check if a user has rich presence
for example, playing, streaming, watching, listening to, ect
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
ty
I don't think its recommended to do things like this
sorry
did u get termed?
mhm for trying to sell my own vanity again
in line 12 and 136 https://www.toptal.com/developers/hastebin/pahobamili.py
sad
@slate swan
damn, had a good tag too
ik
i once got termed and my tag was 0097
Well, lots of elifs are bad
but why didnt work
||switch statements||
Β―_(γ)_/Β―
wdym
lol
is he even using 3.10
no.
?
i had a 0015 tag and got termed which made me so mad cuz 1 and 5 are my fav numbs
i am sure he is not
im using 3.8.2
@boreal ravine can u please look into line 12 and 136 https://www.toptal.com/developers/hastebin/pahobamili.py
rip lmao, i think i still have one of the term emails, it was a fking bible of violations lmao
@slate swan @slate swan @slate swan
rip all my accounts </3
i honestly only get termed for tryna sell my own vanitys but
its like my boost badge gets set back a month each term
why do your accounts get terminated??
ToS
just dont break tos its that easy
stupid things, the most recent one was a 'self harm encouragement' termination, i just told a guy to go stub his toe
He means this.
let variable = "value"
switch (variable) {
case 'value':
console.log("variable is equal to value!")
case 'notValue':
console.log("variable is not equal to value!")
}
the systems bias to me 
he meant in python
I had no clue selling a vanity i worked for was against ToS to sell
it counts as selling discord property
selling anything related to discord is illegal
what does that mean, im new
you cant sell servers accounts or vanitys
Not a thing in Python. I know that it's in only JavaScript.
it is
its in 3.10
It's a JavaScript statement.
im doing python
Is it?
yeah
π can someone please help me with fixing variable shadowing
It's called "match" statement.
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
its just a swtich statement in scooby doo mask
ok
any suggestions on free web hosting services to host my code
They all are bad and can get u ratelimited easily
I need help creating options in slash commands of a Discord bot.
@slash.slash(name="optionTest", description="Test options", guild_ids=[GUILD ID])
async def _optionTest(ctx:SlashContext, message):
if len(message) > 1:
ctx.send(message)
else:
ctx.send("Hello world!")
I want to know how to create optional options, option descriptions.
Please give me a code snippet of how to do this. Thanks~
Which library
hi
We have logged in as None
[youtube] gdZLi9oWNZg: Downloading webpage
[youtube] Downloading just video gdZLi9oWNZg because of --no-playlist
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\91976\PycharmProjects\Beatz\main.py", line 42, in play
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 225, in __init__
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 138, in __init__
self._process = self._spawn_process(args, **kwargs)
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 147, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\91976\AppData\Local\Programs\Python\Python39\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:
ClientException: ffmpeg was not found.```
This is the error I get when try to play a song
I've installed ffmpeg using py pip install ffmpeg
what am I doing wrong here
@client.command()
async def play(ctx, url):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(client.voice_clients, guild=ctx.guild)
if not voice.is_playing():
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['url']
print(URL)
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()
await ctx.send('Bot is playing')```
This is my code
i need a code on how the bot deletes a message(even if its from the bot itself) if the message mentions a word or sentence, the thing is i want it to work only in one specific server,
do you know what FFMPEG_OPTIONS does?
install ffmpeg
You need a code?
I've installed
yes
Use on_message and just have a if statement checking if the message.guild.id is the same one with the one you want
I am getting the error
PyCharm
I've posted my error above @boreal ravine
error
well the error says ClientException: ffmpeg was not found. it means you didnt install ffmpeg yet
Also we dont help with ytdl
!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)
And just have a if statement checking if a word is in the message.content
If so
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleβs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
?
Talking to someone else
if channel.name in [channel.name for channel in some_guild]:
# stuff
ill try
members = len(member.guild.members)
print(members)
bots = len([m for m in member.guild.members if m.bot==True])```
im getting no error but why the data is always so same
does it takes time to update???
is there an event for whenever the member count is updated ????
there's only the on_member_join() event to track if someone joins a server
but i want to fetch the server count on it and many times the server count is same why so
how do u count the number of members
len(member.guild.members) works probably
where did you define member
its a parameter of on_member_join
on_member_join(member)
so can anyone tell me does it takes time to update member count because its nearly almost always same, if it takes time then how much???
How could I block 1 person completely from using my bot
can someone send the link? that i can paste code inside
cuz idk its my luck or its not working
!pate
pathlib
windows-path
relative-path
!paste
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.
async def sometask():
await client.wait_until_ready()
print('task executed')
await asyncio.sleep(5)
client.loop.create_task(sometask())
it only runs the task once why so????
its not a loop
i want it to run every 5 seconds
is this channel dead or wut π© i used to get instant replies here
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
i think thats what im doing, im creating the task
start(*args, **kwargs)```
Starts the internal task in the event loop.
I guess but a bot can only change a channel name once everyone 5 minutes
what ?
Β―_(γ)_/Β―
Nope
what is the function to get user id
then how many seconds should i change status
after every how many seconds
30 ?
is 45 ok?
WHY is rate limits so less
why would you need to change it so fast anyways
60 seconds? π₯Ί
i want people to notice my bot's status change
changing status every 60 seconds is ok right? π₯Ί
I don't know
uhh
Maybe discord API docs have smth
https://discord.com/developers/docs/topics/rate-limits this can be helpful
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
they try to make it ambiguous, so people dont go and push it to the limit
just use common sense for most things
I would say 60 is stretching it, try 120/180
Not every endpoint has an endpoint-specific ratelimit, so for those endpoints there is only the global rate limit applied.
Global Rate Limit
All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations.
No
It's a property
oo ok
Not a function/method
The userβs unique ID.
some of my code raises CheckFailure, how can I handle them in global error handlers?
Just like u handle other errors?
!e
print("```s```")
@sweet geyser :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print("
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 1)
Uhhhh?

Then go in #bot-commands for random commands
oh no my bad
we knew that already
That person used "
why is markdown for about me different for mobile and pc
Is it? Idk
yeah
he says while having nitro and badges
?
Β―_(γ)_/Β―
hello (β―Β°β‘Β°οΌβ―οΈ΅ β»ββ»
it might be smth like this, but how do I make it send the message or what checkfailure happened? ```py
elif isinstance(error, commands.CheckFailure):
await ctx.send(f"CheckFailure on {commands.CheckFailure}")
oo I'll try that
True lmao
quick help with embed
i just want 1 line saying
(mentionsuser) has been unbanned
all ik is
embed = discord.Embed(dont know the rest)
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
lmao hi again
OH
THATS WHAT U MEAN
OMG LEMME TRY
but how do i add it in a code
is it like this?
embed = discord.Embed(discord.Member.mention "has been unbanned")
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
No
get the member object > pass a mention attr to it
example pls?
It gave me this ```
CheckFailure on <class 'discord.ext.commands.errors.CheckFailure'>
did you try what i said
embed= Discord.Embed(description=f"{user.mention} has been warned")
Yep I used {error}
Np plz turn off caps,it looks like u r yellingπ even if you are not
oh uh ty
π
i don't know what you are missing there, try error.original
spoonfeeder
What r u trying to make?
He is not able to understand that's y I helped him
Nothing
well I think i explained it clearly
Simple Error Handling for ext.commands - discord.py - error_handler.py
the member object in this case was user so all he had to do was add a mention attr to it
People don't read sometimes or notices what we have written π
hmm?
People don't know how not to spoonfeed someone also
best alternitive to discord.py?
Check this gist, it may help solving your problem
disnake, nextcord, py-cord, edy, hikari & more
Checkout some of the forks and choose which one suites best for you
i wouldnt ask if i didnt do that
what do you prefer among them
I can't find anything to check failure
oh wait now I noticed what you mean for me to look from there π
does edpy have slash commands
Yes
why
a developer of edpy stole another forks' vanity url
I donβt think so,
that doesnβt make the whole edpy cringe
the lib kinda dead imo
it was not alive in the first place
hm
I did not find anything to get the error message of check failure
cant u just use error
that gives ```
<class 'discord.ext.commands.errors.CheckFailure'>
hm
There are
I use my error handler this way
No issues i got so far
raise CheckFailure('The check functions for command {0.qualified_name} failed.'.format(self))
discord.ext.commands.errors.CheckFailure: The check functions for command mute failed.
``` I'm looking for that message
show the code of your error handler
elif isinstance(error, commands.CheckFailure):
await ctx.send(f"CheckFailure on ({error})")
2 lines
you mean the whole?
Yes
import discord
from discord.ext import commands
import os
import asyncio
import datetime
client = commands.Bot(command_prefix = "? ")
@client.event
async def on_ready():
print("{0.user} is ready!".format(client))
snipe_message_content = None
snipe_message_author = None
snipe_message_discriminator = None
snipe_message_avatar = None
@client.event
async def on_message_delete(message):
global snipe_message_content
global snipe_message_author
global snipe_message_discriminator
global snipe_message_avatar
snipe_message_content = message.content
snipe_message_author = message.author.id
snipe_message_discriminator = message.author.discriminator
snipe_message_avatar = message.author.avatar_url
await asyncio.sleep(60.0)
snipe_message_author = None
snipe_message_content = None
snipe_message_discriminator = None
snipe_message_avatar = None
@client.command()
async def snipe(message):
if snipe_message_content==None:
await message.channel.send("There's nothing to snipe!")
else:
embed = discord.Embed(description=f'{snipe_message_content}', timestamp= datetime.datetime.utcnow(), color= discord.Colour.from_rgb(205, 30, 112))
embed.set_author(name=f"{snipe_message_author}#{snipe_message_discriminator}", icon_url= snipe_message_avatar)
await message.channel.send(embed=embed)
return
@client.event
async def on_message_delete(message):
print(f"{message.author.name} deleted a message: '{message.content}'")
client.run('token')
im trying to make a snipe command but it's always saying "there's nothing to snipe" idk what i did wrong
https://github.com/Nipa-Code/Nipa-bot/blob/master/MyBot/cogs/other/event.py this has most of it the CheckFailure does not exists there
error = getattr(error, 'original', error)
how do i check if channel is in server
I'll try that
This line gives you the original error class,
Try using it above the if-elif statements
help please
wdym
how do i check if channel is in server
if isinstance(ur_channel, discord.abc.GuildChannel)
if there is a channel called {x} in server
!d discord.abc.GuildChannel
class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC...
how about server
The way to check if a channel is of a guild or not
in server
Guild = Server
where do i put server id
Bruh
thank you! It worked
pleasure
i want to see if the channel is in the server
if it is, it sends something
else sends smthing else
You want to know if a chaanel is of a specific server?
yes
well bot is only in 1, private bot
no
in, if there is a channel name called that in the server
You are confusing me 
it checks the server for a channel name
if and else not in server
Can u tell me in brief what are you trying to do?
explicitly
ill try
it checks if a specific channel name is in the server
yes
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
Iterate through your guild channels
ctx.guild.channels?
If a channel with that name exists then It'll return the channels
Or None if no channels were found with that name
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
this returns a list of channel type object. you can iterate through it and then check if channel.name == the required channel name
It contains both text and voice channels
No?
channel= discord.utils.get(ctx.guild.channels, name="ch_name")
?
What do you not understand in that line
did you read this π
what about server
server id
ctx.guild
guild=server ffs
will give the server of the message of the command
where it was written
and .channels is the list of its channels
ill try
if channel1:
await ctx.send(f'The note has been added to \n<#{channel_id}>')
# Channel Found
else:
await ctx.send('Error, class not found or subject not found.')
# No Channel
doesnt work, keeps giving else
Show full code snippet, we are not some magician who can see your code magically and help you debug
@client.command()
async def note(ctx, message=None):
await ctx.send('msg')
msg1 = await client.wait_for("message")
msg2 = msg1.content
msg5 = msg2.lower()
await ctx.send("msg")
msg = await client.wait_for("message")
msg3 = msg.content
msg4 = msg3.lower()
channel = discord.utils.get(client.get_all_channels(), name=f"{msg5}-{msg4}-notes")
await channel.send(message)
channel_id = channel.id
channel1= discord.utils.get(ctx.guild.channels, name=channel)
if channel1:
await ctx.send(f'The note has been added to \n<#{channel_id}>')
# Channel Found
else:
await ctx.send('Error')
# No Channel
Same thing i said hours ago
So how are you taking the channel argπ
...
?
wdym
channel = discord.utils.get(client.get_all_channels(), name=f"{msg5}-{msg4}-notes")
How is that supoosed to be a channel name
it works
also you are not checking the message in wait for
but i need the confirmation
message
if not sent then error msg
We said to use ctx.guild.channels
not sure if this help
;-;
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.
oo thats js
didnt realise that
im noob
this is in d.py
oo
@bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Hello World!')
await message.edit(content='testtest')
how do I get a mesage? It was smth like fetch but I don't remember it
fetch_message?
but it's an api call
hmm
!d discord.abc.Messageable.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
is there another way as well?
what are you going to do with it?
wait idk
@bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Hello World!')
await message.edit(content='testtest')
*with the message
edit/delete messages I guess
lemme google
it's the only way then
from discord import Embed
...
first_embed = Embed(title='embed 1')
new_embed = Embed(title='embed 2')
# send a first message with an embed
msg = await ctx.send(embed=first_embed)
# edit the embed of the message
await msg.edit(embed=new_embed)
```will this work? @slate swan
not a problem
if you want to get the attribute(s) of the message you can use Bot._connection._get_message(id)
this allows a message object as well?
id only
hmm
ok
wait what are you going to do with fetch if you already have the message?
me helping people to stackoverflow things that i dont understand =.=
I'm making a command that gets a message you give it and edits or deletes it
so, how will the user give the message? by replying to it?
by giving message link/id I was not planning of using reply
!d discord.ext.commands.MessageConverter you can use MessageConverter for that
class discord.ext.commands.MessageConverter(*args, **kwargs)```
Converts to a [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.1.
The lookup strategy is as follows (in order)...
item = {
'mobdrop': {
'pogchop' : 0,
'eye_of_ender' : 0
},
'misc':{
'cobble' : 0,
'coal' : 0,
'wood' : 0,
'bed' : 0
},
'illegal': {
'bedrock' : 0,
'bedrock_trophy' : 0,
'pogchamp' : 0
}
}
#######################################################
async def show_inv(message):
res = '__items__\n'
for name, val in item['mobdrop'].items():
res += f"{name}: {val}\n"
res += '__misc__\n'
for name, val in item['misc'].items():
res += f"{name}: {val}\n"
res += '__illegal__\n'
for name, val in item['illegal'].items():
res += f"{name}: {val}\n"
await message.channel.send(res)
#######################################################
if message.content.startswith('rpm i'):
await show_inv(message)
```can someone help me
idk how to make one inv for every user
use database?
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesnβt require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. Itβs also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard HΓ€ring. It provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
that's a db
but im using replit
oh
you can do like
item = {
"user1":{
'mobdrop': {
'pogchop' : 0,
'eye_of_ender' : 0
},
'misc':{
'cobble' : 0,
'coal' : 0,
'wood' : 0,
'bed' : 0
},
'illegal': {
'bedrock' : 0,
'bedrock_trophy' : 0,
'pogchamp' : 0
}
}
}
and give another nested dict for another user
can i kinda like my id is 757508305256972338
in database my inv is store as 757508305256972338inv
something like that
757508305256972338wool = blah blah blah
like a column name
i will modify it later
Hello I am getting this error on heroku
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host lavalink:2333 ssl:default [Name or service not known]
Anyone knows how to solve this?
{"key": "value"}
you are making a music bot, right?
yes
anything
=.=
Oh u again haha
music bots usually break ToS on most services so we can't help on it iirc
then put any key u wan
who

he and me has had a loooong talk on this thing a few days back
Right? Nyon Nyom
to oversimplify this, it's because of rule 5
Yups
yes yes I figured that part. It's not about making bot now. Its about hosting.
without inviting me? evil hunter
I am sure IPayForWinrar also remembers that thing
=.=
Its against tos? I mean hosting.
U were asleep ahem ahem
Why didn't you invite me
π
looks like there is a few master here
π
U weren't there when there was a debate here about free hosts? If not, then idk why I didn't invite u
π
Sure, icy and Andi sure are
wow
Music bots are against ToS on most of services
tons of pro
π₯² ok then
ye groovy and tons of them
Yups
do you know... im bad at coding
yes
Yup
Nope, u ain't
They got sued or discord took action?
how am i not?
ya
This chat be weird
same π©
hmmmm
i dont know coding then
idk what does
print('Hello World!')
``` means >:)
this is quite normal so far
Czzz u write good code?
sarcasm yeah i see
hmmmmm
maybe he can write 1000 lines code without testing
inv system
lemme reply the message
await invites()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns a list of all active instant invites from the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to get this information.
here
use a database
inventory system sry for misleading

but idk where to start
i use replit
replit has a database
you can't actually use a local db on replit
just an ide
replits db is bad
please dont
Joke
i mean it is if you're new to python and want to use a small db i guess
well
i dont need 1000000TB database
replit in first place is not a best choice to host bot on
is not a good choice*
unrelated
Yes, Heroku better and If you use VPS its best
idk how to get user id with bot
The userβs unique ID.
@tawdry perch you need to type in the full class name
I don't know it so I just put smth that I remember
doesn't work like other bots sadly
but how do i get it
get ?
just id = discord.user.id?
kinda save it in database
no
you need a User instance
im thinking to save things in database like (id)wool = blahblah
it isnt that simple
;-;
Use a real db, replit db is a joke
14 Sep 2020 β I think repl.it is great for prototyping or teaching, but it is NOT the "best place to build your apps".
NOT the best place to build your apps π€£
heroku is better?
yes
but i need to download stuff to use heroku?
No
You need to setup some stuffs
@bot.event
async def on_member_remove(member):
channel = bot.get_channel(802458136006885386)
await channel.send(f"Bye {member.username}\n\n\n{member.username} just left the server.")
Why this isn't working?
@loud junco this has smth for setup
thanks
wdymπ
you can run half a month for 24/7 (as well free) but full month for free with credit card info
the bot
Heroku ain't no bot
can i run the bot 247?
for half a month without credit card
=.=
Yes but It has limited dyno hours
will the keep_alive thing help?
no
or have 2 accounts, can't share database if you use smth like sqlite. You need to use server based db
you don't need keep alive
.
2 accounts?
.
i dun und
1 account = half a moth. Second account = half a month
at least deploy your bot for the first time, youβll know by urself later
but nvm lemme switch my code to heroku first
ye
thanks im going to eat
intents?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I spend half a month to improve my bot and second half to run it hosted in heroku
theres no function for that
!d discord.ClientUser.avatar
property avatar: Optional[discord.asset.Asset]```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientUser.display_avatar "discord.ClientUser.display_avatar").
its a property fyi
I was thinking of postgres but I don't think I can share it in between 2 accounts
I've added that
if you know the hostname and password you can
oh wait
2 accounts
idk
Is it correct? ```py
msgs = await self.bot.fetch_message(message)
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
@tawdry perch
I thought it needed bot there as well :/
y the class
Wrong if u r using 2.0
how to do this -> step 1: make a git repo with all of your bot files
U using heroku?
im trying to switch my code to heroku
Ah
cuz u say heroku is better
Well, best of luck then hehe. Lemme tell u the steps
or can i just skip step 1
-> step 1: make a git repo with all of your bot files
-> step 2: go to your heroku account, create a new app (located in US, will get your average bot latency to under 30ms 100% of the time)
-> step 3: go to settings and add python buildpack, then click "Reveal Config Vars" and add your bot token, along with whatever you have in your .env there
-> step 4: go to deploy, select Github, connect your github account, then select your bot's repo
-> step 5: make sure your bot has a `Procfile` which has "worker: python main.py" (or whatever the file that runs your bot is) and a requirements.txt where you have your requirements listed in newlines
-> step 6: go to overview, click Configure Dynos and then click that pencil icon and toggle the button then click Confirm
-> step 7: make sure you have 2 heroku accounts and switch between them at the end of each month (when you get an email from heroku saying that you're running out of dynos, they refresh at the start of each month)
-> step 8: done
And git repo means u gotta use git
lol
Do u know whTs git?
Yes
but idk how to repo
