#discord-bots
1 messages ¡ Page 627 of 1
im trying to make the command ignore users who it can not dm, including itself
Maybe. In which case it'd be continue.
otherwise, dm
Can you show the whole function?
Yeahđ
kept raising the error non stop
until sherlock told me that error handlers exist for a reason
botid = [913528283281358948]
@bot.event
async def on_guild_join(ctx):
if discord.User.id in botid:
pass
for member in bot.get_all_members():
#stuff
await ctx.send(embed=embed)
print(f'done')```
thats what i have right now
then use return
i think....
return would cancel the execution if im not wrong
Are you tring to dm all members in a guild?
isn't that what you want to do?
looks like it
you did botid
i want the bot to dm the ppl its going to be added to, but ignore itself, and users who have dms off (arent messagable)
so DM everyone in the server?
instead of bot.id, ik, im making it read the check
just passing an if conditional is same as not having it
yes, its very few people but regardless
Use a try and except if their dms are off it wont do anything
No it doesnât. It does exactly what it looks like it does. It returns nothing.
ok
And just use ctx.guild.members
and why botid that's wrong
(they also want the id as well)
its for a list
You need to put the if statement inside the loop. So like:
@bot.event
async def on_guild_join(ctx):
for member in bot.get_all_members():
if member.id == bot_id:
continue
await ctx.send(embed=embed)
print(f'done')
``` ish
What do you mean by "aliases"?
ill try that4
test = ctx.guild.members.id
continue skips the current iteration
that was a test to see if you can get the ids
so like, an alias for != would be is not
or you can make a for loop
its not an alias
Err, there's no "alias" for continue.
both have different uses
And yeah, != and is not are different operators.
unless they mean
@client.command(aliases=["test"])
but I dont think so
not that
Pass = ignores
returns = returns
continue = keeps going
break = breaks the func
oh i see

breaks the loop*
*return returns nothing
Thatđ
dementati too fast :/
and return has to be in a func as well
No returns the outputđ
dementati too smort
this would prevent the bot from dming itself right?
ofc it's dementati
he's a demon at python
It would skip whatever you are doing later in the current loop iteration if the current member is the bot.
"keeps going" might not be the best words to describe it,
it skips the current iteration
And wouldn't dming all members get you rate limited
Whatever
!e
for i in range(30):
continue
print("it wont work")
@sullen shoal :warning: Your eval job has completed with return code 0.
[No output]


!e
for i in range(30):
pass
print("test")
@velvet tinsel :white_check_mark: Your eval job has completed with return code 0.
001 | test
002 | test
003 | test
004 | test
005 | test
006 | test
007 | test
008 | test
009 | test
010 | test
011 | test
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jusuyuhaho.txt?noredirect
damn
thats its job
im dead
Are you okđ
no
đ
5:30pm
Gn
I mean you're a programmer. Sounds pretty normal to meâŚ
Gn
Yeah
Im kinda feeling like a crazy person
So ima use json as a dbđ
Json is not a database tho
Thats the point
I'm kinda feeling like a crazy person, so I'mma travel into the city on a kid's tricycle.
That's what that sounds like.
It's like, sure, you can do that, and it'll get you there eventually. But it's not efficient.
Thats the point json isnt suited for it lmao
I mean tbh json isnât meant for config either but people still use it. Crazy world.
Yeahđ
This chat is always dead in the evenings but mostly active in the morning and nights
That depends on where you live.
Ig ppl are enthusiastic and full of ideas in the morning and give up on their project by the evening
Do yall still use dpy or did u switch to different fork?
can someone help me with this problem. im not that good at python so im not sure how to create and save instances of classes for each user. this is what i have but it never remembers that the class for the user exists
not crazy enough
Code?
I'm going to code python on an enigma
dont ask to ask
It's not super crazy, it's just... I dunno, not a good idea.
I'm gonna code python on an engima, I'm that crazy
@bot.event
async def on_guild_join(ctx):
members = ctx.guild.members
for member in members:
try:
#embed stuff
await member.send(embed=embed)
print(f'done')
except:
print("Something went wrong")```
error: ``` members = ctx.guild.members
AttributeError: 'Guild' object has no attribute 'guild'
An enigma is not Turing-complete, so that won't work.
That's like saying I'm gonna go into the city by riding a washing machine.
Parameter is not ctx, Itâ s guild
It's a machine, but it's not a vehicle.
so just guild.members?
NameError: name 'guild' is not defined```, should i do discord.Guild?
!paste Would you mind using the service described in the box below to paste your code instead of a screenshot? It's easier to read this way.
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.
on_guild_join(guild: discord.Guild)
Itâ s not ctx
Itâ s discord.Guild
so just async def on_guild_join(guild : discord.Guild): not async def on_guild_join(ctx, guild : discord.Guild):
Yeah
Yes
Look it up in docs
Disnake is one of the best forks
Love the pfp
Ty
Beautiful walter
Tyty
so it recognizes that the instance of the class named with the users id exists until the next event
then it says the instance doesnt exist
Tbh most of the forks that people made are complete garbage. Especially that edpy shit. Said theyâd stay with Dannyâs original design and keep everything original. And guess what. Itâs like a completely different library.
What is this supposed to do?
Iâll honestly stay with the main library until it breaks. Then move to novus.
im trying to figure out how to create classes for each user who types in the discord. like a profile
Disnake is same and it has support for slash commands and components and since I mainly use that I just went with disnake
Its same syntax but a bit complicated relating to buttons
Most of the components on dpys master branch
Slash commands arenât even that special. To me they are just shitty versions of message commands.
The fact that discord is wanting people to go to them is baffling.
Ig u could create user entity and save it into db via some orm
It actually makes buttons easier with disnake.ui
Yeah ik
Yea but classic commands wont be supported anymore
Thatâs depends
If you're bots not verified you can continue to use them.
If you're bots verified figure out a way to get message intent.
Wont they be removing them in 2022?
If you have automated mod features youâll more than likely get accepted for the intent.
Message intent is mainly for on_message event
Your bot wonât able to read message content anymore and know if someoneâs trying to invoke a message command.
So discord.py will be useless w/o support for slash commands
Not really.
Rip carl-bot
Privledged intent enforcement is towards verified bots.
Carl has auto-mod features. If the owner applies for the intent, nothing will probably change.
It probably already has it
đ¤ˇââď¸
Otherwise it wouldnât be able to use on message event
And idk how they would make automod without it
No đ¤Śââď¸. Every bot can still operate as normal until they start enforcing the intent some time in 2022
But u alr need to apply for the intent if u verified?
can apply
If u need it
They opened the applications early
Where can I read that stuff
Do they have it on dev portal?
I fr thought they were gonna completely wipe classic commands
ddevs
Ty
Thatâs where they make the announcements about all that stuff.
Lemme see
It says u can still get content of the message where bot is mentioned in
đ¤ˇââď¸
They will just make it so u cant see message content
Basically uwill still know when someone sent something but u wont know what they sent, except in dms or if bot is mentioned
it won't let me create bot inv link
?
help
@bot.event
async def on_guild_join(guild : discord.Guild):
members = guild.members
for member in members:
try:
#embed stuff
await member.send(embed=embed)
asyncio.sleep(2)
print(f'dmed {member.name}#{member.discriminator}')
except:
print("Something went wrong")``` when the execution finishes, the console gets flodded with "Something Went Wrong", how can i close the loop after all the members are dmed? and how can i limit it to 1 DM per 2 seconds? to prevent ratelimits
pls
What are you trying to do
Send code
when the bot joins the server i put it in, i want it to dm the users in the server. how can i limit it to 1 dm per 2 seconds to prevent getting ratelimited?
You have to go to url
For member in members:
send message
asyncio.sleep
for member in members:
try:
#embed stuff
await member.send(embed=embed)
asyncio.sleep(2)``` like this?
The exception ur getting could be something else
@slate swan dont use a bare exception
So just remove try clause and see what errors u get
Just remove try clause for now
except Exception as e:
print(e)
Just remove the try clause
Itâ s bad practice to just catch every exception
asyncio.sleep(2)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
Await asyncio.sleep
ohhh right
await asyncio.sleep(3)
Its a coroutine it must be awaited
?
Also if you get an exception it helps to read it
In bot theirs 2 tabs
Theirs a url to make a button for a bot and another for a random url invite
I got it to wrk
Nice!
@zenith basin btw your nickname is wrong
Pip should be lower case: pip install Wolf
can someone explain what pass_context = True means?
Its not really needed anymore
its deprecated, but it basically made ctx an optional/required argument
now ctx is always required
Okay, I've just seen it in some examples and I was confused as to what it was
Thanks guys
most examples are crap
Yeah
Your welcome!
does anyone have python command to bring bot online?
Wdym
What?
What do you mean?
Forgets...

I think he means like⌠if the botâs replit (for example) is stopped then is it possible to turn it on
With a command
(I think)
I dont think so
https://oml.wtf/tNub1Rsm i just noticed this, hows groovy not have a status?
it just...chooses not to have one :p
I donât think so either, since if whatever the bot is running on is currently stopped.. the command wonât even work 
That's what I meant
Yeah, itâs not possible I donât think
Since the bot wonât take any commands if itâs off
you make a second backup bot
Yeah thats just nonsense
Yeah lol
Because they set an interaction endpoint URL
Seems like groovy has switched to fully interaction based stuff?
The bot is on, it is just waiting for commands on an HTTP server
Because I made my own implementation for interactions over HTTP
I did the same thing to my test client and noticed it lost a presence but still received commands
Although commands as in interactions only
It doesn't have any websocket unless you do HTTP Interaction and websocket combined
I seeđ¤
Thats coolđ¤ 
Pretty cool yes, but I had no idea this is what happened until like a week later
how can i do that
When I was testing INTERACTION_CREATE dispatching I wasn't receiving it
Until I realized I set the endpoint
You do it on the developer portal, although I wouldn't do it unless you know what your doing with interactions
okay
I mean, you will still receive events if your using gateway but you won't receive INTERACTION_CREATE
And if you want to receive it you need a HTTP server that verifies a requests is from discord
You make my head hurt
Me too
Your very knowledgeable about those types of topics like servers,and backend stuff
Not really
Yes really,but how did you learn about those types of topics
Makes sense,i mean i do it here because everybody is always talking about stuff i dont know but i learn from it
Read articles
And work on projects
I do
If ur into backend u can also learn a framework like django or quarkus
Yeah i am
Check out quarkus
Idk im not really lean to web development
What are u lean to?
Idrk ig anything related to apis
Api is a contract on how two applications interact
Yeah ik
Literally every library u use has an api
Api is not related to web
Or rest service
Yes as backend developer you need to create a good and logical api that frontent dev will use
hey guys, every time i try to have my bot send a DM to the author of the message, nothing happens and I get no errors...
What is happening???
Code?
Wait doesnt a back end dev make use of a api?
# REGISTERS THE USER // CREATES ACCOUNT IN masterdbmac.sqlite DATABASE
@commands.command()
async def register(self, ctx):
await ctx.send("Hey!")
uid = ''.join(random.choice(string.ascii_letters) for i in range(5))
await self.send(ctx.author, f"Your unique ID is {uid}.")
Send ss of code
Wait doesnt a back end dev make use of a api?
He can use a 3rd party api if ge needs to
self.send()?
Then whats a dev that uses apis to make programs ?
its in a cog
A front end?
Just use ctx.author.send
? that works?
Every dev uses apis to make programs
Ima look at some articles
Yes
I have lmao
Read about what an api is
I have bruh
Lemme give u an article
I've been checking on the internet about it and everything is saying client.send
Why would i use a api when i dont even know what it is
What is an API? (Application Programming Interface) API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, youâre using an API. What exactly is an API? Finall...
Well what do you think an api is then
Read the official docs
!d discord.Member.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**.
I see now. Everything else was telling me how to do it when it was separate from an event
Also Itâ s bot not client
yeah so if I have self.bot = bot at the top of the code
Itâ s self.bot then
Not self
And you dont have it at the top, you put it in a constructor hopefully
its under the whole def __init__ thing
Yes that is good
Oh I see, it's self.bot not self
Yes
ok got it
Still use ctx.author.send
And api is basically like a translator
?
well, in short; youâre wrong.
I mean in your perspective but i really didn't specified it really
the dpy library is a wrapper for the discord API
Yeah?
yup
Lol
otherwise you'd be using this https://discord.com/developers/docs/intro
Integrate your service with Discord â whether it's a bot or a game or whatever your wildest imagination can come up with.
Yeah
Whats your take on a api personally i think its a tranlater example
english is the back end and the user is spanish and the api is the translater that knows both languages.am i wrong?
hmm i don't think that's quite the right analogy. it's more like the API end points are little lego pieces and the dpy library is a wrapper which lets you build using those lego pieces with its predefined classes
idk if that's the best analogy either tbh 
Kinda seems the same to me,but thats a good example
Made a YouTube music streaming feature for my bot, but I am confused with the following line of code:
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
I understand the function of single and double asterisks when declaring functions, but why are there two asterisks before FFMPEG_OPTIONS?
How would I make my bot do something if someone starts typing in a specific channel?
streaming youtube media outside of official platform options is against their tos so please don't ask here
Theirs something for it but i forgot it,check docs
Damnit I forgot docs was a thing
got it. still a valid question though, no?
Mb lol
Yeah sorry
Oh no itâs fine, I need to start reading docs before asking
Yeah its better practice 
Yeah lol
!ytdl @bronze pilot sorry we dont help with stuff that break tos
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)
APIs are just services which you can use to communicate to other services
ye I was told already
Yeah but not the reason
So basically what i said?
Yea basically
Looking on docs it says discord.on_typing so would it be like
@client.event
async def on_typing(<channel id>):
#<code>
?
Yeah i knew that guy was tripping
Idrk cuz i havent checked it out 
I think so
Alr lol, sorry for bothering, Ill try it out and if you want Ill let you know if it works 
No its alr, okie
can someone help?
Maybe
Whats the error?
idk

Nothing wrong
First dont change your presence on_ready event
The red underline
o wait why not?
why tho

its normal but today its like
When the bot is connecting to the gateway and a event happens discord will disconnect you because its a atom action
Do a task for it
Will that happen everytime?
No but it is a atom action
Which i do not recommend
Hmmm, so how would I use a task for it?
async def startup():
#change presence etc
bot.task.create_loop(startup())
Maybe the bottom will give you a error i forgot its kinda long
@cerulean osprey btw atom means:
an action that cannot be interrupted
Hmmm, so this is currently my on_ready
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
poiu = random.choice(songs)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str(poiu)))
bert = client.get_channel(898815070207877133)
await bert.send('I have come online once more')
So as of now, nothing so far has happened for it to error. Is it maybe bc of the print statement making sure the bot is ready before running the change presence?
No not at all
Or have I just been lucky 
Its just discord sometimes disconnects you because as said its a atom action
Yes
its bot.loop.create_task()
Damn, alright so it would be
async def startup():
#<change presence witchcraft>
bot.loop.creat_task(startup())```
?
Yeh
thank you
Forgot the e in create
What is the problem right now?
Oh yeah 
Whats with the create_task here
As of right now nothing, but just wanna make sure nothing happens in the future so Im moving my change presence from on_ready to a task

^
I mean
commands.Bot(activity=..., ...)
That works fine too
This will set the presence directly when IDENTIFYING
Which is done when connecting to the gateway
The bots disconnects when its trying to connect to the gateway or when the bots cache is loading?
The change_presence and disconnection issue is to some weird fuckery with READY event and what not iirc
So in this case, my presence is set by a random song from a set list, so would I move that list above commands.Bot() and do
poiu = random.choice(songs)
client = commands.Bot(activity = client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str(poiu))), ...)```?
No you just pass the discord.Activity instead of client.change_presence
Bruh i was told it disconnects you cause discord doesnt like when you do it
I want a discord bot to create a voice channel
So other than that, yeah?
Should be right
Lemme try
Well, I mean basically you could word it like that ig
Still confused if its cuz if the gateway or the cacheđ
gateway
Thx 
but iirc discord.py reconnects on 1006 right?
Wtf why that numberđ
How can I make a Discord.py bot make a voice channel?
1006? There isn't an error code like that on discord API unless you mean websocket close code
And I'm unsure how discord.py reconnects so I can't say
yeah
But at least from my experience the websocket only reconnects when it receives a RECONNECT OpCode
Being 7
client = commands.Bot(command_prefix="-",
help_command = None,
poiu = random.choice(songs)
activity = discord.Activity(type=discord.ActivityType.listening, name=str(poiu)))
``` its giving me an error on the `activity` line
I do know that discord.py has an exponential backoff when connecting so that could be what you mean
Show the error, and why are you assigning poiu inside of the constructor????
"Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it."
at least from the tag
Yea, it would be 1006 websocket close code
Yk that is a good question, I just copy and pasted what I had in the on_ready 
And the error is just invalid syntax
Heres the RFC
the it should reconnect then? Why would change_presence in on_ready a problem
It shouldn't reconnect cause it errored thus cancelling the connection. But like I said earlier discord.py has an exponential backoff for when they connect which can reconnect the websocket maybe
Straight from docs
ok
Yw
And after reading this closer, seems like for whatever reason sending the presence payload to the websocket during the time frame of READY being dispatched fucked something up
Can't be sure of it unless discord dev have disclosed it alr or smthg as we can't see the source I don't think
and this?
oh
This is just discord.py doing a reconnect


Oh nvm its erroring at something else that I added but was highlighting the activity line.. that makes sense đ so I need help again bc Im a little confused as you will see in the code Imma provide
@client.event
async def on_typing(channel=909685766244945921):
await channel.send(f'Woah, {<@{user.id}>}! Before you send your message, just be warned, you will be softbanned if you message here!')
``` this is designed to warn people before they send messages in my spam catcher channel, but Im not exactly sure how to ping them. The thing I tried was an honest shot in the dark and had no real expectations of working. How would I ping them?
I'm not versed in all of discord.py's internals so it can be the exponential backoff or something else
!d discord.on_typing
discord.on_typing(channel, user, when)```
Called when someone begins typing a message.
The `channel` parameter can be a [`abc.Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") instance. Which could either be [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel"), [`GroupChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.GroupChannel "discord.GroupChannel"), or [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel").
If the `channel` is a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") then the `user` parameter is a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"), otherwise it is a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
This requires [`Intents.typing`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.typing "discord.Intents.typing") to be enabled.
Yeah I read that on docs lol, but how would I ping them?
So user.mention?
Yes
TypeError: on_typing() takes from 0 to 1 positional arguments but 3 were given :o
!e ```py
def func(): ...
func(1, 2, 3)
@pliant gulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: func() takes 0 positional arguments but 3 were given
You can see why this would error right?
Yeah, but if you are abt to ask me to explain then I cant bc idk how to word it 
Ok well if you know why it is erroring then you should know how to fix it right
Yes, but also no. Ik that I would have to do on_typing(channel=<id>, user=<insert thing you put for user>, when=<insert thing> but idk how to fill in the last two
And when I leave it at user it yells at me
No, you wouldn't do channel=
You just add the parameters to the function signature like the doc showed
!e ```py
def func(param): ...
func(1)
@pliant gulch :warning: Your eval job has completed with return code 0.
[No output]
Ohhhhhhhhh 
đ¤
So then what would I put for the other 2 then? Just user and when?
What do you think?
I think that when I do it still yells at me with scary red underlining 
Can you show what you are doing exactly
async def on_typing(909685766244945921, user, when):


How do I print something when someone replied to one of my bot's msgs?
on_message and look message.author and message.reference
Reference
Bc I wanted to set it to a specific channel and have 0 clue how to do it with on_typing() so I just attempted to guess
um, @pliant gulch https://github.com/Rapptz/discord.py/blob/master/discord/gateway.py#L582 this thing reconnects by raising an Exception?
discord/gateway.py line 582
raise ReconnectWebSocket(self.shard_id) from None```
Yea so I was right earlier
They use exponential backoff to reconnect
await ctx.author.send("Create a username.")
check = message_check(channel=ctx.author.dm_channel)
username = await self.bot.wait_for("message", timeout=30.0, check=check)
await ctx.author.send(f"Your username is {username}")
Can someone tell me why this is returning this:
Your username is <Message id=913584734020440104 channel=<DMChannel id=913566891073744967 recipient=<User id=326903703422500866 name='Kazido' discriminator='0139' bot=False>> type=<MessageType.default: 0> author=<User id=326903703422500866 name='Kazido' discriminator='0139' bot=False> flags=<MessageFlags value=0>>
oh it's handled https://github.com/Rapptz/discord.py/blob/master/discord/client.py#L513 here
@client.event
async def on_guild_channel_create(channel):
#things
in the things comment, I want to check if the channel is a voice channel or a text channel
discord/client.py line 513
except ReconnectWebSocket as e:```
username is discord.Message currently
How would I convert that to a string? str(username) just puts the same thing in..
if channel.type in (ChannelType.voice, ChannelType.text): ...
convert what?
if you string the message, it would appear like that
basically I want their response to be a string that I can store as a variable
How to search for a video using ytdl??
do you mean the message content?
yeah!
!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)
channeltype not defined
I am not misusing ytdl
make it message.content
discord.ChannelType
Finding youtube videos is not against YouTube ToS
username.content*
got it thanks
you cant find videos with ytdl
You sure?
googleapis are shit
_query = parse.urlencode({'search_query': "video title"})
_content = request.urlopen('http://www.youtube.com/results?' + _query)
_results = re.findall(r'/watch\?v=(.{11})', _content.read().decode())
```I found this somewhere in the past (still work tho currently)
Phew I don't wanna scrape
I need help
Ask for it already
@client.event
async def on_guild_channel_create(channel):
I wanna check if channel is vc or text, Its still not working
stop rushing me
still not working
I am sorry
im using repl to code discord bots and when i type "import discord" this happens , can someone help?
run pip install discord in shell
Use their packager to download discord
oh how?
there is package on the left
Sometimes installing from shell doesn't work
it should, but elaborate "not working"
There is a cube on the left side
ohhh
is it version 1.7.3?
its just not working, like error
Yup
Install the first one
show the error
if channel.type in (discord.ChannelType.voice, discord.hannelType.text):
is that it??
discord.hannelType is wrong
You missed a C
if channel.type in (discord.ChannelType.voice, discord.ChannelType.text):â
1 sec lemme try again
Yes if its not the main branch
How to check user's spotify activity??
!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").
!d discord.Spotify
class discord.Spotify```
Represents a Spotify listening activity from Discord. This is a special case of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that makes it easier to work with the Spotify integration.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activityâs hash.
str(x) Returns the string âSpotifyâ.
Forgot to mention
Using direct API
Why do u even wanna use the direct API bro
Cuz why not
It's a good practice
Breh I ain't kidding
To improve skills IG
Hmm ty for trying
GET /guilds/{guild_id}/members/{member_id} then use the response header and get 'activities' key
Oh tysm

Ah, headers. Hmm
help pls
Hi so I am trying to give somebody a role via my bot and I was wondering, what argument do I put in the add_roles()?
you are defining your bot as nextcord.ext.commands.bot as it should be ``nextcord.ext.commands.Bot()`
discord.Role object
you can get it via Guild.get_role()
@visual island
.
defaultRole = role = Guild.get_role(defaultRoleID)
Is this correct?
from nextcord.ext.commands import Bot
?
no, guild should be Guild instance
not directly the class
Im confused lol
show where you define your bot
client = commands.Bot(command_prefix="!", intents=intents)
not you
you would be using an instance of the class , ie. Not just the actual class
Which you get from any attribute like ctx or message
like ctx.guild or something
ah I'm guessing that youre using commands.bot import in the cog file and using it in the Cog
show your imports in this file
thx
So wait does it required to be in a function
and this help @visual island
GUYS
HI
I MESSED UP
use self.bot.latency too
thx
i wanted to put a reminder everyday at 8 30 but this ended up happening
no, you can use bot.get_guild() for the guild too
Ok im confused even more, what code do I have to write to make a variable for my role ?
where are you trying to add the role?
this shld work right?
read it
I cant understand the problem
Go you your developer portal and enable intents
No problem
I am adding it in a on_member_join but I dont want to define the variable in that function
member.guild.get_role(...)
What do I put for member, as I said im not defining it inside of the on_member_join
!eval py import datetime from datetime now = datetime.now() dt_string = now.strftime("%H %M") print(dt_string)
@gloomy coral :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | import datetime from datetime
003 | ^^^^
004 | SyntaxError: invalid syntax
why?
from datetime import datetime
you defined it in the parameter
aaah
But im not defining the variable in the on_member_join?
is that a problem?
My question is, if im not defining my role variable inside of the on_member_join, what do I make the "member" in the member.guild.get_role(...)
oh
just use bot.get_guild() for the guild then
why would you convert it to int?
you can just do if dt_string == "15 00" or ...:
ok
So do I just have a seperate var that says guild = client.get_guild() then?
ok
yes
@visual island this will work now?
@tasks.loop(seconds=60) # repeat after every 40 seconds
async def checkVoteTime(self):
await self.bot.wait_until_ready()
channel = self.bot.get_channel(880639248292798465)
now = datetime.now()
dt_string = now.strftime("%H %M")
if dt_string == "15 00" or dt_string == "03 00":
vote = nextcord.Embed(title="This is your reminder", description="You better vote for me, here and now", color=nextcord.Color.random())
vote.add_field(name="1", value=f"[top.gg](https://top.gg/bot/864010316424806451/vote)")
vote.add_field(name="2", value=f"[discordbotlist.com](https://discordbotlist.com/bots/chad-6621/upvote)")
vote.set_thumbnail(url="https://i.imgur.com/QICgRpf.png")
await channel.send(embed=vote, content="<@&881209363077943326>")
else:
pass
@tasks.loop(seconds=60)
async def csv_update(self):
await self.bot.wait_until_ready()
now = datetime.now()
dt_string = now.strftime("%H %M")
if dt_string == "12 00":
date1 = datetime.strftime(datetime.now(), "%a, %d/%m/%Y")
data = [date1, len(self.bot.users)]
with open("databases/members.csv", 'a+', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(data)
date2 = datetime.strftime(datetime.now(), "%a, %d/%m/%Y")
data = [date2, len(self.bot.guilds)]
with open("databases/servers.csv", 'a+', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(data)```
earlier it was sending msges many times
sure
how can I paginate the data from an api ?
what's wrong?
https://github.com/Rapptz/discord-ext-menus you can use this or use your own pagination system
this sent at
so shldnt it not sent now
cuz i want it exactly at this time
wuts the prob
https://paste.pythondiscord.com/ekotuhebez.py
probably cause it's using your local timezone?
try using utcnow
thanks
the theme is awesome which IDE?
how do i make a text channel with permissions only for a certain user (im using a ticket system and don't want to use roles)
i think vim
Well the basic idea is that that channel need to be private and visible only for the user and thesupport team members
Isnt it
yeop
Oh
But there are 2 prob , 1 how wud you add that person only 2 how wud you know the supportteam member as every server has different names
ic
uhh why?
because I want to make the bot run faster
if anything it will make it slower
ticket_channel = await ctx.guild.create_text_channel("ticket-{}".format(ticket_number))
await ticket_channel.set_permissions(ctx.guild.get_role(ctx.guild.id), send_messages=False, read_messages=False)
for role_id in data["valid-roles"]:
role = ctx.guild.get_role(role_id)
await ticket_channel.set_permissions(role, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
await ticket_channel.set_permissions(ctx.author, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
em = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "{}".format(message_content), color=0x00a8ff)
await ticket_channel.send(embed=em)
@shrewd kraken
this might work
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.
I can send some more code if you cant figure out
no need
I wanna run threads with discord.py
I cant send discord's message limittoo
can anyone help?
for what
I dont have experience
for making it run faster
But I have a bot
most of the time threading can make it slower
I don't think threading would make discord.py faster
Their ratelimiter uses Lock's thus allowing only one thread in at a time
^ exactly
So requests would be bound to one thread at a time
shameless flex but my api wrapper allows concurrent requests as I use semaphores instead of locks
although i think using multiprocessing with an eval cmd might work
do u have slash commadns
how?
I do sorta they are half implemented
do they work in cogs
I haven't tested that but with cogs they should work?
Hey @dark pawn!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
⢠If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
⢠If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
@client.command()
async def say(ctx,*,msgsay):
async def do():
await ctx.message.delete()
await ctx.send(msgsay)
t = threading.Thread(target=do).start()
for example, threading doesnt work with this because I need an await inside of it
you could use it to execute your command
but i wouldnt recommend it
how??
in eval
wdym
idk but its possible but it might be slower
multiprocessing is basically threading but better
Hey, I am getting this error:
2021-11-26T04:04:56.609535+00:00 app[worker.1]: Traceback (most recent call last):
2021-11-26T04:04:56.609556+00:00 app[worker.1]: File "/app/main.py", line 24, in <module>
2021-11-26T04:04:56.609655+00:00 app[worker.1]: defaultRole = guild.get_role(defaultRoleID)
2021-11-26T04:04:56.609679+00:00 app[worker.1]: AttributeError: 'NoneType' object has no attribute 'get_role'
2021-11-26T04:04:56.737460+00:00 heroku[worker.1]: Process exited with status 1
This is what I have:
serverID = config['serverID']
guild = client.get_guild(serverID)
defaultRoleID = config["roleIDs"]["defaultRoleID"]
defaultRole = guild.get_role(defaultRoleID)
Anyone know my issue?
how do I use that?
what's config
{
"roleIDs": {
"defaultRoleID": 912534307443183646
},
"channelIDs": {
"systemMessagesChannelID": 913090699254190110
},
"serverID": 911418973118165042
}
Json file
huhh
Here let me simplify
serverID = 911418973118165042
guild = client.get_guild(serverID)
defaultRoleID = 912534307443183646
defaultRole = guild.get_role(defaultRoleID)
That is my code essentially ^^
you cant use threading with async functions
-_-
what?
no forget local its supposed to be called at 3:00 vps timezone
ur srs?
its me using nano in terminal
ok
Can anyone helphow to add local time ina embed
@commands.Cog.listener()
async def on_ready(self,):
print("Suggestion cog loaded successfully")
em = discord.Embed(title ="Monitor Up",description=f"Antimatter Monitor Up At(GMT) ",color =0x00b300)
em.add_field(name="Time",value=x.strftime("%X"))
channel = self.client.get_channel(912594498398326814)
channeldev = self.client.get_channel(912320086516318288)
await channel.send(embed=em)
await channeldev.send(embed=em)
This iswhat Imade butI want the time in my local time which is ist(gmt+5.30)
is there a reason commands arent working for me
Probably because u coded something wrong
Wait what
<t:1637900336>
i never code wrong. its always perfect first try
I want in my bot
Yeah do the same in ur bot
Can anybody help?
BOT , what a stupid thing to have
so why are you here?
Thats not nice 
Lmao aternos
what
đ discord bots bad?
for some reason, when trying to get a commands.Context.author it returns NoneType? i dont see how or why? i even tried chunking the guild yet no luck.
can anyone figure out why my command is doing literally nothing at the bottom of my code?
dm
whats your error
do you get the except part everytime?
no first time
Do you have an on_message event?
restart the bot
dont think thats the issue else the commandnotfound wont be raised
It is.
There is no command processing either way
even if commands werent being processed, it wouldnt raise a CommandNotFound error, it would simply do nothing.
There still is no command processing
ÂŻ_(ă)_/ÂŻ
ÂŻ\_(ă)_/ÂŻ
not working
no error now
there is , the bot checks that the message begins with the prefix
worked now
nvm
There is no command processing... Just look the screenshot sent.....
And it's not a @bot.listen so it will never process the command
right, but if this were to be their issue, it would not raise a CommandNotFound error
correct me if im wrong?
Well I'm surprised it even processes the commands with a normal on_message event overwriting
on_message events "may" block the code , its not important that it always does.
I'm pretty sure it always does
As you overwrite the default one, which contains processing stuff, with your custom code which doesn't.
import discord
from discord.ext import commands
TOKEN = ''
client = commands.Bot(command_prefix='-')
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
client.run(TOKEN)```
why this does not work .-.
whats your error
um yea , but as you can see it wont raise the commandnotfound error
(line12 is bot.run)
someone already told you about that on_message thing in lucas' server , did you fix it?
oof lol
yes i did
show the on_message event you have now
how can I check if something is in a message
@client.command()
async def mute(ctx, member: discord.Member, time=None, *, reason=None):
format = datetime.now(tz=pytz.timezone('America/Tijuana'))
formatted = format.strftime("%I:%M %p")
b = DT.datetime.now().timestamp()
modlogs = client.get_channel(872909569196707870)
db = await aiosqlite.connect('database.db')
cursor = await db.execute('SELECT * FROM mutes')
rows = await cursor.fetchall()
muted = discord.utils.get(ctx.guild.roles, name="Muted")
farmer = discord.utils.get(ctx.guild.roles, name="Farmers")
apprentice = discord.utils.get(ctx.guild.roles, id=907127783849861120)
if ctx.message.author.guild_permissions.administrator:
if member is None:
e = await ctx.reply('You must mention someone to mute!')
await asyncio.sleep(5)
await e.delete()
await ctx.message.delete()
return
if time is None:
a = await ctx.reply('Please state a time for a timed mute or a reason for a permanent mute!')
await asyncio.sleep(5)
await a.delete()
await ctx.message.delete()
return
if reason is None:
if time[-1] in ['s', 'm', 'h', 'd']:``` This is quite messy, but is there a way that I can somehow determine if the `s`, `m`, `h`, and `d` are touching another letter, if so it does something?
```py
if time[-1] in ['s', 'm', 'h', 'd']:``` after this line.
Use pytimeparse to parse time
Could you explain?
You can get message content as string by doing discord.Message.content
Google pytimeparse
Itâ s a library which u can use to parse time periods
I'm not sure if that'll help me fully xd
When I try to do .mute @hollow agate Spam Bot, it determines that as a s so it tries to put seconds- everything else works.
NoâŚ
Interesting, is there not a better way? I'll need to rewrite my entire command and it's quite a lot in there
Can u send a ss of command
hey guys, what would some general code look like for an if statement that checks to see if a user reacted to a message in a DM with a certain reaction?
I'm trying some code rn, but it's not working and no errors are coming through
@commands.Cog.listener()
async def on_reaction_add(reaction, user):
if reaction.emoji == 'â
':
await ctx.author.send("Adding account to database...")
Is this right?
Show ss of code
Can u send ss
Cus I cant read this on mobile
I'm on a mac and I'm not sure how to do it lol
hi
Command shift 4
Itâ s shift + cmd + 4
Hi
Shift cmd? Didn't know u could do that
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnât require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itâs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
đ
U can't get it here
You dont have context parameter
It only works on command
U have user
Use user.send
AH okay
Can u use user without adding user:discord.Member as a parameter
!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...
He can still define it using get_context
Yea I see, I mean in the ss he sent
Yes, doing :discord.Member is just type-hinting which is not necessary in python
No. user will not be passed, and thus wouldn't be available for use
unless you're talking about the :discord.Member part
Yes
If u want this to work with non cached messages too use on_raw_reaction_add
What does non cached messages mean?
Messages that are not in cache
what
Error?
Maybe try making it a str first
basically using the raw version would make your event work for all messages, rather than only on messages sent after the bot connected to discord
Oh okay, thank you for explaining
Just use raw version
You should try and see if it fixes the problem yeah
I did, and it didn't lol
Code?
It probably has something to do with the fact that it's being reacted to in a DM
send full code
Did u read the docs of on_raw_reaction add before doing it?
Because if you just changed the name it wont work
the raw version doesn't have those parameters
It's mostly creating an embed, sending it, adding reactions to it, and then waiting for a reaction
read the docs
Now go into docs and look up which parameters does raw version take
It has payload
lmao what would i put for payload
Docs
Ye i was just there
you could also instead use wait_for, which would be much preferred here
Did u read,
@slate swan I was trying to user wait_for earlier but it was giving me some trouble. Couldn't figure out the try: thing
the try and except thing?
All u need
yeah, I was confused with the whole def check() thing and such
So @cedar stream which one of those from that list would go in the parameters??
I don't know what to pick
you could just use ```
check=lambda r: r.channel == some_channel
Those are attributes of the parameter
just payload
U put in payload
Das it?
yes
ok it still didn't work đŚ
error?
No error bro, idk what is happening
Show code
full code
Send ss
paste it, don't screenshor
I cant read pasted
for this ENTIRE cog?
no
Cus on mobile
only the things related to your problem
No just event
e.g. the event and the embed construction etc
Just send a ss of event and then paste the code
yeah
Itâ s underlined red
@keen talon
I asked him cus I can read it easier on mobile
just send the code
Oh ok đ
Basically you dont have user parameter anymore so you need to get it from payload
# REGISTERS THE USER // CREATES ACCOUNT IN masterdbmac.sqlite DATABASE
@commands.command()
async def register(self, ctx):
temp_uid_check = []
stored_uids = (c.execute("SELECT * from uids WHERE uniqueids = uniqueids").fetchall()) # DATABASE OF CURRENT UIDS
stored_uids = convert_tuple_multi(stored_uids)
for x in stored_uids:
temp_uid_check.append(x)
# GENERATE NEW UID
uid = ''.join(random.choice(string.ascii_letters) for i in range(5))
while uid in temp_uid_check:
# IF THE UNIQUE ID ALREADY EXISTS, CREATE A NEW ONE
print("This UID already exists. Generating another one.")
uid = ''.join(random.choice(string.ascii_letters) for i in range(5))
# IF THE UNIQUE ID DOESN'T ALREADY EXIST
else:
# def acc_creationcheck(m: discord.Message):
# return m.author == ctx.message.author and str(reaction.emoji) == 'â
'
check = message_check(channel=ctx.author.dm_channel)
acc_start_embed = discord.Embed(title="Account Creation Started", description="What will your username be?",
color=discord.Colour.dark_grey())
await ctx.author.send(embed=acc_start_embed)
username = await self.bot.wait_for(event = "message", timeout=30.0, check=check)
acc_confirm_embed = discord.Embed(title=f"Create Account", description="Your account information is below. Please keep these!", color=discord.Colour.green())
acc_confirm_embed.add_field(name="Username", value=f"{username.content}", inline=True)
acc_confirm_embed.add_field(name="Unique ID", value=f"{uid}", inline=True)
acc_confirm_embed.add_field(name="Create account?", value="React with â
to confirm your account creation.", inline=False)
acc_confirm_embed.set_footer(text="Please remember your Unique ID. You will need it in the future.")
acc_confirm_message = await ctx.author.send(embed=acc_confirm_embed)
await acc_confirm_message.add_reaction('â
')
await acc_confirm_message.add_reaction('â')
@commands.Cog.listener()
async def on_raw_reaction_add(payload):
if payload.emoji == 'â
':
await user.send("Adding account to database...")
await asyncio.sleep(0.2)
with conn:
c.execute("INSERT INTO uids VALUES (:uniqueid)", {'uniqueid': uid})
c.execute("INSERT INTO users VALUES (:username, :id, :level, :experience, :coins)",
{'username': username.content, 'id': uid, 'level': 1, 'experience': 0,
'coins': 0})
await user.send("Account created successfully!")
elif payload.emoji == 'â':
await user.send("Account creation terminated.")
Itâ s underlined red
IE payload.user.send?
get user first
payload.member
In my opinion, u should use mongo db for the data
oh payload.member
payload.member.send
No. I'm not learning more code. I just learned how to use SQlite and im a beginner to this stuff
Alright then đ
Wouldn't I have to learn a bunch of new syntax??
not really
It is very easy tbh
surely there must be python libraries to interact with a mongodb database
U donât necessarily need mongo here since he wont be having billions of rows in each table
wtf man I wish this thing would give me som fuckin errors
Pymongo, motor, MongoEngine, MotorEngine
does the embed sending and reacting work?
I run code, do things, get 0 errors
But the format of data will suit mongo ig
Look at all red underlined things
Yes. It works up until I react to the message. Then nothing happens
that could mean the event isn't being triggered
Yeah, i wish my app would tell me that
Use print statements to check
put a print at the beginning of the event and try reacting
len(guild.members)
either way, im probably gonna have to change to the wait_for thing
where would I put a print???? I already have the payload.member.send, would i just put print above that?
at the beginning of the ebent
