#discord-bots
1 messages · Page 606 of 1
no
then.... do you have intents?
why the codes doesn't work tho
For people who are demotivating sherlock did not learn dpy in a day did they?
Did you actually add the role id
have what?
I started with dpy on my first day of Python
yes
indents*
!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.
Ok
no
It's not about d.py. He is literally trying to code bots in discord.py on his first day in Python. That's bad practice.
intents are different stuff
makes sense but still
Intents is the permission so the bot sees other members
no i dont
oh icic
Don't blame me haha
i use replit to code it
wasnt it hard and all spaghetti tho
lemme get something for u

Ye. My first bot was an on_message bot which would spam a channel if I sent even one single message in it 🤣
some people are able to do it, but most will find it extremely hard and frustrating
Facts
all
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
Understand, don’t memorize.
xd
People already experienced with Ruby, LUA, etc probably can jump right into it without finding it that hard
Or heroku*
yes
do I have to import
get aws 1 year free trial
because they are experienced, all they need to know is the syntax
Yeah
not in python
Error
python's discord lib is a lot more experienced than that
Ruby and LUA are very similar to Python. They'll just need to brush up on some basics which they can do in an hour or two, and then jump right into d.py.
its all objects and classes and nothing
Source: I know both py and rb
it depends on popularity
error.
however using the decorators might take some time
some pro ruby programmer could make a discord api wrapper
Says it in the traceback
Even an intermediate will be able to program a simple API wrapper, though not one with a lot of features (such as d.py or d.rb)
Yes def
i didnt slap the ticks
slap them
hats off to danny
I slapped em
for the structure this good
now no error but not sure if works
js is currently leading at discord bots
however the cogs could have been a little better
I tried making 2 @bot.command in 1 file but I came upon an error
is there anything js isn't good at
actually I tried to make a help command but it said that, that already existed
I am 100% sure I havent made any help commands yet
it does defaultly
why
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
bot = commands.Bot(help_command=None)
would solve it
or doing it the right way just like Myxi's tag says
where will i put dat
you dont need to suffer from all that
Ok none would be able to help can u send a tutorial for the bot basics a link or something
🤣 this is what happens when u have the guilds scope in your OAuth URL
lol
just use the class

you either put the kwarg there or make a help command the right way

Hehe those are my guilds' info
Yeah ik
hecker
Ye
make the text green tho
Why tho
it will look hecker
mf also sent my email id 🤣
of?
IKRRRRRR
well everything
😭
read the docs
This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Want more from Mike? He's starting a coding RPG/Bootcamp - https://simulator.dev/
⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello Wor...
Hey, why does get(bot.guilds, id=741774567907******) return None?
here
that would be expensive
oh-
no please not youtube
.......
tutorial for python
xd
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
this isn't dpy
NOOOOOOOOOOOOOOOOOO
Can someone pls help me? ;-;
😭
yes
youtube tuts are bad never watch them, the official python tutorial is good
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
can only recommend 👍
He is my dad...
wha
Yea...

💀
Why you even say that 😭
😔
!d discord.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
im sorry i gotta be careful about my words now 😔
||It was a joke 🤣||
But that is a fact. Be careful with your words
Your grandfather 
@sullen shoal sorry for that ;-;
perhaps the *
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
either that or invalid ID
instead you could just do bot.get_guild()
ohh I could try that yes
afaik get probably has O(n^2) and bot.get_guild() is just O(1)
np
still returns None
Then it couldn't find it ig
your intents are probably not set right then
hm
Prob
if i code it through Visual Studio Code then the bot will be always online??
oh thats possible
huh
the bot will be online as long as your script is running
No who said that?
Im zsed to my old bot having all intents
visual studio code is at a very basic level a text editor
Its not like replit
then how do I make the script run forever
if you want your bot to always be online either buy a raspberry pi, or a good VPS both of which you cost you money
Get a vps
Bingo
raspberry pi has a heavy initial downpay, but it's worth it after you pay off the initial investment. VPS will be a per-month basis often. AWS afaik charges you on cents/hour of uptime
If I put my computer into sleep mode will the script still running?
depends on the ACPI power state
HAHA yes I forgot discord.Intents.all() thanks a lot
assuming your intents are correct, then the ID is invalid
Code:-
async with ctx.typing():
subreddit = reddit.subreddit(sub)
all_subs=[]
top = subreddit.top(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
author = random_sub.author
author_link = f"https://www.reddit.com/user/{author}/"
postid = random_sub.id
embed = discord.Embed(title = name, url = url, color=0xf80707, timestamp=ctx.message.created_at)
embed.set_image(url=url)
embed.add_field(name="Post author:", value=f"/u/[{author}]({author_link})")
embed.add_field(name="Post Id:", value=postid)
embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url = ctx.author.avatar_url)
Error:-
Command raised an exception: AttributeError: 'str' object has no attribute 'subreddit'
```....wut do i do?
(i have a laptop) the battery died so its always with the charger so does that make it run when the pc goes to sleep mode? (no turning off)
really depends on the acpi power state like i said
different computers go into different states on sleep, try it and see if it works
File "/home/container/main.py", line 44, in <module>
print(f"[L] Support Guild: {supportguild.name} -/- {supportguild.id}")
AttributeError: 'NoneType' object has no attribute 'name'
the ID is correct
if i were to guess your reddit variable is set to something else
i.e you have multiple reddit variables
maybe it's in your command argument that takes in a subreddit name?
i gave tht sub
odd, can you post full traceback?
this...wud make sense...lemme see
wait if I copy the id on pc its...
741774567907000391
And on mobile
741774567907000391
It is the correct ID 
Wait Ill change to bot.get_guild again
I just dont kinda like those API calls
fetch() always does a api call
Well then I switched something lmao
I remember something like that did an API call so I thought it was get_guild lmao
get() takes from the bots cache if none then it wont do anything
Anybody know why sometimes stuff isnt in the bots cache like a channel id?
Maybe because the cache is at the limit?
Prob
I mean you can change the cache limit in Client()
Default should be 1000
iirc
No :oogh: that’s not how that works.
Please explain
Was just a thought, thats why maybe
A user won’t be in the bots cache if the member isn’t in any of the bots guilds.
Well anyways get_guild() still returns None
Guess your bots not in that guild
No like sometimes stuff isnt in the bots cache
So you have to fetch it
Well actually hold on.
my code is
supportguild = bot.get_guild(741774567907000391)
You might be right here. Just thought about the max_messages kwarg in the Bot init.
You forgot await
if I want to code it in VSC i need to make the poetry.lock and the pyproject.toml files in my folder?
ohhh
No poetry is just an optional package manager
makes sense
You can just use pip
oof its not in a function...
Doesnt that need await?
Like its ... a global var
I swear it did
no
fetch does
get doesn't
;-;
get() definetly doesnt thats what I know
Why does my bot have await before get() and still work😭
Depends if the function is sync or async
But
Why I get "Warnings" (yellow lines) when I want to import discord
import discord #<-- yellow line
from discord.exe #<-- yellow line
get isnt async
do you have discord installed on your pc?
Is discord installed?
pip install discord
warnings
that should show a error like py TypeError: object User can't be used in 'await' expression lol
do pip install discord
install the library
Never has
cmd?
yeah
Its in a corountine so maybe its that
get ain't async
How can I delete a message with only a message ID?
pip is not recognized as an internal or external command.

get_user is not a coro
so i tried this thingy on jishaku py await _bot.get_user(_ctx.author.id)
and got this error py TypeError: object User can't be used in 'await' expression
install pip lol
have you put python in environment variables?
No i ment bot get channel
if not
no get function is a coro
I just downloaded python 3.10.0
even get_channel aint , a normal def will result into same error
No
did you click on 'add pip to path'?
py -m pip install discord.py
It hasnt😭
something downloading
owh , maybe your error handler eats up that error , or that part never got executed
yes
Doesnt have one😭
And it actually gets the channel with no error
👀 now im interested in seeing that code , could you?
Cant😔
get() is a sync function, even the docs say that 😆
update it then
..
your problem?
...h-
pip install --upgrade pip
not recognized
py -m pip install --upgrade pip
Help, there's no spaces on my embed message, and i wanna add 1 space between each field i add. How do i do that?
You can't. Discord embeds are quite limiting
unless you mean putting them on seperate lines
In which case, you can pass in the inline=False argument into the discord.Embed object
This is the line but it still works with no error
c = await bot.get_channel(b).send(embed=embed1)
yeah so its basically await a TextChannel.send()
.embed add_field(name, value, inline=True)
Makes more sense😭
i recommend installing the beta version
but it requires git
Nice emoji
beta version has select menus and buttons
no, i mean with a invisible character. But as far as i know, the method i tried, adds 3 spaces and not one
!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.
can i close the cmd?
Hmmm
VSC
oh- alr
Invisible characters are just meh and don't work on all system. My server uses some invisible characters in the channel names, it shows up as wierd boxes on my linux development machine
?
yeah i still have the warnings
yeah
there is a autoban for scamlink
error
async def on_message(message):
if "ticket." in message.channel.topic:
return
if message.author.bot:
return
if "ticket" not in message.channel.name:
return
else:
if "" in message.content.lower(
):
await message.channel.send(
f"{message.author.mention}, an **ARK Admin** will help you os")
await message.channel.edit(topic="ticket.")```
Why this doesnt work
what did you write?
pip install python
me?
i. already. did. that.
no
LMAO
it works when i remove: if "ticket." in message.channel.topic: return but i want it there
VDP , restart vsc after pip installing the library
when i went to my folder to open it a tab opened saying "Updating Visual Studio Code"
ok
Can someone help me please
Sure, ask your question
async def on_message(message):
if "ticket." in message.channel.topic:
return
if message.author.bot:
return
if "ticket" not in message.channel.name:
return
else:
if "" in message.content.lower(
):
await message.channel.send(
f"{message.author.mention}, an **ARK Admin** will help you os")
await message.channel.edit(topic="ticket.")```
Why this doesnt work
Define "it doesn't work"
How can I have the bot check for a reaction
it does when i remove: if "ticket." in message.channel.topic: return but i want it there
What doesn't work? What do you want it to do? What actually happens? What errors occur? All these are important in diagnosing issues.
Do you want to check on_reaction ?
!d bot.wait_for
No documentation found for the requested symbol.
Ok
so
!d discord.ext.commands.Bot.wait_for
if ticket is in the channel topic, stop the code
if ticket is not in the channel's name, return
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
if "ticket." is in the channel name, no commands will work there. Is that intended behaviour?
I want to change channel topic and at the same time check if the channel has a specific topic and if it does return
in the topic
topic is name is it not?
no
oh okay, my bad
discord-bots is the channel name
For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
what could be the issue
is the channel topic
I see, gotcha
We still don't know what the issue is
k
the problem is the logic
Um I want to run the command and the following hqppen
-
[Cmd run]
Check for messages containing reaction ✅
If it has it check for reaction ☑️
(Prevents duplicate copys)
-
idk how to fix it
okay it opened now I can code here and it will work correctly?
commands will only run in channels that have "ticket." in the description. is that what you want?
nvm it's a listen, commands will work
nope
and wtf is if "" in message.content.lower( ):
huh
So if ✅ == True you want to check if ☑️ == True and so on? (It's not like this just to show it)
no need
you don't have to
so it triggers every message xdd
it triggers every message either way
yes
that's a really big skill issue bro
there's no point
you need that in replit
oof ik
I want it to make sure there is a green check but not a blue check
i started days ago
So I just do bot.run(os('TOKEN')) (I will put my bot's token here)
so im still learning
There's your mistake
yea, ig
You should not attempt to work with the discord.py library as a beginner, it is not meant for beginners and is an advanced library
Ohh so if ✅ == True && ☑️ == False ?
no cuz I remember u being here before 
i left it
Yes
and came again
I see okay. Give me a sec
and i also remember u
my bot isnt getting online
It takes a hot minute
Did you add a token?
Yeah
no I am dumb... OFC I DID
then give it a minute or 2
No need to get aggressive 
@sick birch Did you found the issue already?
Are you using replit?
no
I don't know what the problem is lol
Oh alright
i am using Visual Studio CODE
Did you make a on_ready event
@kind wind your commands should still work if it doesn't show up on the online list
Yeah^
I went and copy pasted all my work into VSC
Given you're connected to the gateway servers of course
I got an "error" popup
Show
That would've been useful to know
Ofc your bot won't run if it gets a error
Fr
I have never coded a bot in python
It is my 1st time
Yeah you probably shouldn't
I am just telling you what I see in hope I will get it running
Like I said before the discord.py library is quite a complex library and is therefore not suited for beginners
bot still not up
You should first have a firm understanding of intermediate Python before progressing with discord bots
!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.
That's not really possible without external parsing, you can however ping the role or give the ID
The amount of people I see doing this lmao
Same
I assume they all follow those bad tutorials that use client for the commands.Bot
Free code camp
Yeah
good naming practices = very important
Still not online
Yes
Can we see your code then?
Did you downloaded the py ext in vsc?
Ah that
Did you find how to do it?
pretty sure I did
Nah man, sorry
I assume the C# extension was the one causing the .NET error
Does anyone know how to check for a reaction on a message
Do a check
uninstalling cuz i never used C#. If I need it i will download it again
good idea
How do I do that?
message.reactions
it's either discord.Reaction or discord.Reactions i'm not fully sure
I wrote a bot that returns a table of information. Often times, the table is more than 2k characters. Can anyone point me a direction of how to split this message into multiple responses please?
I tried the following, but I keep getting the message too long error:
I think I found why my bot doesnt go up
I just found that I have been getting a traceback the entire time
its about the run
yeah
TypeError: 'module' object is not callable
I am not sure how this works
but how do i fix it
What colorcode is this? I want to use a HTML code is that possible aswell?
thank you
this is the error i'm getting:
In content: Must be 2000 or fewer in length.
ffs
how do i make it show the user badge on userinfo command?
Does anyone have an example on how to check for a message that has a reaction
message.reactions
Uhh what do I use that with
if message.reactions:
# message has reactions
else:
# message does not have reactions
message.reactions returns a list of discord.Reaction objects, by the way
Does that list messages with the reaction in the channel or what
Heyy, im trying to make a music bot and im running into this issue
AttributeError: 'NoneType' object has no attribute 'is_playing'
No, it only lists the reactions of a specific message
No it's a list and it won't send on it's own
YOOOO GUESS WHAT
Finding all messages in a channel with a reaction would be quite time consuming
Depending on the server size of course
So I have to list a message ID?
Yes
YAYAYAYAYAYAYAYAYAY
But I suppose if you wanted to loop through each message, and check if message.reactions is a falsy value you can
Message intents?
@sick birch
you would need the message object, not the ID
Verification
though you can obtain said object from the ID
Ah awesome
I have also submitted for messages intent, let's see what happens
How di I get object?
TextChannel.get_message(ID)
fetch_message(ID) would also work if you wish to make an API request
!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.
Nothing like this lol
I know, i'm only provide psuedocode
Ah, my bad
wouldn't want to spoonfeed would we haha
True hahaha
So
message = await fetch_message(id=Mid)
If message.reactions:
#message has reactions
Else
#message as no reactions```
Would that work?
no
fetch_message is a method of a discord.TextChannel object
and id doesn't have to be a keyword-argument
@commands.command(aliases=["delete", "Delete","DELETE"])
async def _delete(self,ctx,message_id=None,channel=None,reason=None):
msg = await ctx.get_message(channel, message_id)
await ctx.delete_message(msg)
reason_channel = await ctx.get_channel(902223345217581086)
deleted_message_embed = discord.Embed(
title = "**Advertisement Deleted**",
description = f"**Message ID:** {message_id} \n"
"**Reason:** {reason}"
,color = discord.Color.purple()
)
await ctx.send(reason_channel,embed=deleted_message_embed)
Can someone help me with this?
What's the problem?
I believe most of the attributes are just wrongly used
Who can drop the code for cleaning and get ban?
but I'm unsure which ones are the correct ones for it
What?
Yea, it has to be a pos arg, else it will raise an error
Then what is reccomended
await ctx.guild.ban(member, reason=reason) is the code for ban
thanks
Please don't spoonfeed
Ok so I want a bot that checks after 30 mins on a website that does it have the true statement on it, if it does then I want it to send a msg in a channel saying: "Hey, {user} is now online.". is it possible? https://paste.pythondiscord.com/iqalujasoq.md <-- there's my current command code
I'd need the time module and the if else statements right?
Hmm, lemme see
Okay don't use requests
It's blocking
!blocking read this embed for more information (;
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
hmm ok
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
Okok
time.sleep is blocking, not asyncio.sleep
1 min
Ping me if u need any other help (:
Alright
https://paste.pythondiscord.com/yojotatele.py
My problem is that it doesent say any thing when the variable " who " changes (await ctx.send() just sends message)
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
Oh, hmm
Did u try printing the variable?
no
Try printing it
found my prob
Yay
Aw
U gotta do a while True loop or something
Or multiple wait_for's inside your loop
this might be dumb of me but as i try to create a help command it tells me there is already help command and its not a command sooooo
Cool
try doing client.remove_command("help")
help_command=None in your bot constructor. Dpy makes a default help command for u haha
@maiden fable hey I'm back
very helpful
!d discord.ext.commands.DefaultHelpCommand is what it uses by default
class discord.ext.commands.DefaultHelpCommand(*args, **kwargs)```
The implementation of the default help command.
This inherits from [`HelpCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HelpCommand "discord.ext.commands.HelpCommand").
It extends it with the following attributes.
or that, yeah
now would you be willing to help?
thanks it worke
I am always willing haha
:D
Preferred is to do the bot constructor thingy tho, but okay
Ok so I use asyncio and what other module?
aiohttp instead of requests
asyncio instead of time
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").
you talking to me?
Yea
idk that it even existed
It's sort of a while True loop with an asyncio.sleep at last
:/
hmm ok
It's fine. Click the link, there are some examples of tasks!
okok
So they repeatedly do something at equal intervals of time
whats the differnece
Like checking a website after 30 mins?
I need this beacuse I wanna stalk my friend, he unfriended me in game
Nothing, but the bot constructor way is cleaner haha and a bit more pythonic according to me
Sure.
Yups
Suppose u add a bot command and after that call that method, then that remove command would get removed
!d aiohttp
Thanks
!d is equal to !docs which is the docs command of @unkempt canyon
Ok cool
Then what would you recommend
He told u haha
how can i get banlist of a server
the 2 messages i sent after
U need a TextChannel instance
guild.bans
while authorhealth > 0 and memberhealth > 0:
who = randint(1,2)
if who == 1:
I changed it like this and it still doesent work
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
can you do that example code thing of the aiohttp module?
What?
I'll just scroll up
Uhhh, wym by that?
ah yes that
Well, I don't really know about your game, but why not just use buttons and see if the user clicked the button. If he does, then break the loop
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
if i type this as:
guild = ctx.guild
await ctx.send(guild.bans)
``` work?
@maiden fable Let's say, I don't want to switch over to aiohttp, I just wanna stalk 1 person am I good to use requests?
!paste can u use this please?
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.
sorry it's not a property, it's a coro
ok
sorry i said it was i forgot haha
If it's a private bot, then sure
np, ty 🙂
yea it's a private bot
don't use it for any actual projects
Yea
requests is blocking in an asynchronous environment
What about the time module do I have to switch over to asyncio?
Imagine if I use requests in my AI Chatbot which gets its responses from my API 😂
Yes.
that would be bad, indeed
ok
Do u know what's the best debug?
I'll google an example code of tasks
i think if it's just a quick and dirty tasks there's nothing wrong with going the simpler method
!d discord.ext.tasks.Loop click the link
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").
The example is there in the docs
no
oh well... time to read all the docs
Printing the variables which u think are causing problems and adding print statements to random lines so that u can see which line is being executed and which isn't
Not a bad thing
vscode has a really nice debugger as well
bit more sophisticated but it does its job well
Yeah
also sorry for the unrealated question, but is an iPhone 6 good in 2021?
Wait till you see other modules' docs haha
subjective
Idk, I don't use iPhones
F
7 would be good
:/
I got gifted an iPhone 6
!ot tho
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
7 plus would do you great
How to use that debugger tho? Isn't that only for interpreting errors?
Hey everyone
just asking
Not bad either
:D
you can keep track of stack calls & variable values at certain times
Pretty good for simple stuff and not hardcore gaming
random lines ?
Isn't that only at those times when there is an error?
coroutine is this read as co routine?
Error: confuses me
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 51
async def msg(ctx, mid):
^
SyntaxError: invalid syntax
[Program finished]```
nah you can use it whenever
I don't play mobile games, when I have a good PC
Yeah
Like print statements with random things (preferably numbers), every 2 lines or something so thT u know which are being executed
Then youll be a o k
How? U mean adding a Breakpoint?
tho discord lags
nah theres a little thing on the left that shows what values variables are currently
Yeah it will a bit
i don't really use it though (old habits die hard ) haha
Idk that comes up for me only when there's a runtime error 😂
oh weird, it's the 3rd button from the top on the left bar
you can pull it up anytime
so you want to tell me I listened to you?
Nono I mean, the variables and their values are shown only when there is an error. The tab is always there
@maiden fable I a m c o n f u s e d
Wym
it shows even when there are no errors, go figure haha
I d o n ' t u n d e r s t a n d t h e d o c s .
What's up with this error
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.
Bro... Dpy has the best docs I have ever seen, like literally the best
:/
U forgot a closing bracket somewhere above the line
Yea...
how do i get a category ID by its name
!d discord.utils.get
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...
async def my_background_task():
await client.wait_until_ready()
channel = client.get_channel(id=909981604129157181)
while not client.is_closed():
await channel.send('\n'.join(C))
#print(str(channel.last_message.content))
await asyncio.sleep(200)```
I want to send message every x seconds but I don't want the bot to spam the same message. (C) can varry. How do I make the bot read it's previous message while in a loop so I could send a new message only if its a different one..
It's a type of channel
you said I should do that

Yea, u should print the variables and add print statements (debug prints) so thT u can see which lines are being executed and what are the variables values
:/ flex

U gotta save the message in a variable, like message = await ctx.send()
I remember the time I had nitro
how?
print(var-name)...
Simple print statements
w h a t
It helps you know which parts of your code are running and which aren’t
That wasn't for u lol
@maiden fable could you send an example of what I should do to use tasks in my code? here's my code https://paste.pythondiscord.com/iqalujasoq.py
Ik this is the wrong server but anyone here who can help me with hosting a discrod bot written in kotlin and java i have the source code
so ctx is going to be that message I send? I could just do print ctx and it would print the message content the bot send?
Leave tasks... Just do a while True loop lol
Nonono
ctx is from your command
Use epikhost
Get a VPS
there're no commands its a loop
Yes please
AWS is arguable the best hosting service in the world
big words, I don't understand
:D
Then u r doing channel.send()?
U can just do message = await channel.send() then haha
sometimes this channel is overloaded, but sometimes dead asf
^^
big brain moment
@sick birch can ya help him please? I am already sleepy since it's past 12 here 😐
No lol. Sort Of Basic Python
Just goto sleep then
the problem is it not repeating the while even though the statement is true
ikr
Tf?
I see
Sorry OTTER, I don't really know what could be wrong, I am on a mobile, so can't really help with big codes rn, sorry
AWS
and @sick birch's offline
how can i add a command alias
does disc py allow while loops that are long? stupid question
Not for me tho
Yea....?
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
!d discord.ext.commands.Command.aliases
The list of aliases the command can be invoked under.
looks like you're doing,
import discord
discord()```
kind of thing somewhere in your code. tracebacks help to find the place
@(ur thing).command(aliases='')
ok
Oh add
that is fixed
Nvm, my bad 🤦
I am really sleepy, gn
Good night
it should be aliases=["alias1", "alias2"]
Gn g
hm but then I get ALL the data from the message not just content. What's the best method to extract content from it? Regex find?
you get a .Message object
which has the .content attribute
so you can just do message.content
which will return the message's content
thanks I just wanted to ask for docs
👍
discord.Guild.roles will return a list of discord.Role of the guild. You can iterate through the list and use in statement (not sure if its called statement) to check if role name is in the message content. If it is, add the current element of the iteration to target
nvm this method wouldn't work anyway because it's referenced before assignment
ok
how can i do so bot edits a channel name only by adding 2 numbers
for example from ticket-1111 to ticket-111122
database
oof
the crap way would be to iterate through the list of channels of the guild then find the channel with the highest number then add 2 to it then do whatever you want
very hard to me...
so use a database
i dont even know how to start so i wont be able
Str it and add 22 then int it
hm¿?
ticket = str(ticket)
ticket += "22"
https://paste.pythondiscord.com/iqalujasoq.py ok so I want to make a command that when I say ,stalk (Username) it should goto the hyperlands api website and check if there is the word "True" if there is I want it to Send a DM to me, if it didn't find it I want it to wait 30 mins and try again
im making a ticket system but doesn't work
async def ticket(ctx):
guild = ctx.guild
embed = discord.Embed(
title = 'Ticket system',
description = 'React :envelope_with_arrow: to make a ticket.',
color = 0
)
embed.set_footer(text="ticket system")
msg = await ctx.send(embed=embed)
await msg.add_reaction(":envelope_with_arrow:")
reaction = await msg.fetch_message(msg.id)
await client.wait_for("reaction_add")
await client.wait_for("reaction_add")
if reaction == ':envelope_with_arrow:':
await guild.create_text_channel(name=f'ticket - {reaction.author.name}')```
yeah sorry what's the problem @regal shard
bruh
i'm at school so i went offline haha
When do you guys recommend jumping to another programming language and what do you guys recommend i thought about c# or js
need some help+
https://paste.pythondiscord.com/ebigoxigur.py it doesn't repeat saying who's turn it is
I would say knowing about objects, classes, OOP is enough
then you just need some cheatsheet to jump
it seems like these days everyone and their mother use javascript, knowing a good bit of that will come in handy
I see when should i jump?
whenever you want there's really nothing stopping you from doing it
Sorry for late reply
I thought when i feel ready or when i need it because i dont want to learn it without using it because ill forget it
I was alsp afk lemme get it
heeyy someone can help me please
could you send an example of what I should do to use tasks in my code? here's my code https://paste.pythondiscord.com/iqalujasoq.py
personally i got bored with python for a while, i have phases like that, i was learning stuff with JS then like electron and node
F
that's great, applying the skills you learn is just as important as learning them
I only know python, autohotkey, and a little bit of HTML
that 34 lines of code looks like it is begging for using dataclasses
Just wanna learn js cause i wanna be a backend software engineer and i feel like i would need it
yep, learn node, express, react/angular/vue/svlete
and hey you can also make discord bots in js 😉
@bot.user_command(name="pp",alias="penis")
async def pp(ctx,member=None):
member = discord.Member or ctx.author
await ctx.send(":eggplant: Looking in your pants ...", delete_after=2)
await asyncio.sleep(2)
sizes = ['=', '==', '===', '====', '=====', '======', '=======', '========', '=========', '==========', '===========', '============']
pp = random.choice(sizes)
embed = discord.Embed(title="Penis size", description=f"{member.name}'s penis size is:\n8{pp}D",color=discord.Colour.red())
await ctx.send(embed=embed)```
please use the random module more
pp
😂
Is that a bug?
change member.name to {discord.Member.name}
also string multiplication is a thing
Robin mate can you help me now?
no way
print("="*5)
Output
=====
idc
!e
print("="*5)
@regal shard :white_check_mark: Your eval job has completed with return code 0.
=====
:D
no if thats so then ctx.author will result in an error
member is discord.Member or ctx.author
;-;
!e
import random
print("="*random.randint(1, 10))
@sick birch :white_check_mark: Your eval job has completed with return code 0.
=========
hmm
thats a great idea
it really is
tysm
idk i kinda want to do this idk why
string multiplication does that to you 😂
!e
print("="*__import__("random").randint(0,10))```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
==========
idk why i did that tho
@sick birch
why do you need tasks for this
idk I Hunting the hunter said I should use tasks for it
can u help?
it needs a dataclass thats it
Why discord turns russian symbols into Дура
I post request to api/v9/channels/example/message
sure i'll try my best
notice how bedwars stats are in ['stats']['bedwars']
yea?
you can do something like:
bedwars = stats['stats']['bedwars']
bedwars_wins = bedwars['wins']
you can apply that to everything else
Good idea
because you're repeating things a lot
true
also add some line breaks between the different gamemodes
bedwars should be in one chunk, skywars in another, etc...
The code isn't meant to be public, + I can read it fine
extra work
:(
aight then not an issue
ok so how would I make it check it every 30 mins
tasks
yes but what is that? 🤔
but I want it to be a stalking cmd
so just run the stats command
each time it's run it will make a request to the hypixel api
*hyperlands
sorry
Nah it's fine
but yeah it should return the updated info
yes I know that
unless you want it to be like constantly updated in one message
but since my friend unfriended me from there, I don't know when he is online I just wanna stalk his profile
kinda like a timer but with stats
yeah just run the command whenever you wanna stalk his profile
What is the best thing for a music system or does disnake come with it? I don't see anything relating to music on the disnake api.
i mean if you really really wanted to
you can just run it once
and always check it it will have the latest info
I already have a command like that
I just want it to send me a msg when he comes online
there's not official support for illegal stuff like that so you gotta lookup github projects and stuff
not wanna rethink life choices :/
ohhhh
i get it now 😂
;-;
!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)
finally
sorry my brain doesn't work half the time
Same
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
self.index = 0
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
Exmaple from the docs
ouch that's a shame. Love youtubedl
it's almost been 2 hours since I started asking for help :D
this will run the printer function every 5 seconds
you can adapt it to what you want
okok
i.e set it to 30 minutes
@tasks.loop(minutes=30)
anything within that function will be run every 30 minutes
if you find out that your friend is online, have it ping you or DM you or whatever
1 question
!d discord.on_member_update this event will be triggered whenever a user changes the following but not limited to:
status (online, offline, dnd, idle)
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
I'm not using cogs + have never used them in my entire life
they're talking about their status on minecraft, not on discord
I didn't complete the message. However, you may read it in the docs.
could you make it so that it's without cogs
What does that have to do with discord.py, though?
they want their bot to be able to alert them when a specific player is online on mc
You may learn about them in this repository. https://github.com/ScopesCodez/discordpy-cogs
not really sure, check out the tasks documentation tho
it get's it from the hyperlands api

