#discord-bots
1 messages Β· Page 51 of 1
You pass in your ID as an integer rather than a string
π
example pls
I'm not sure how I can provide an example, just pass in an integer? It's a primitive datatype
It happens more often than you think haha
intents is now a required kwarg in defining a Client or a Bot.
Better wording: "intents are now a required keyword argument when initiating a Client or Bot."
You should specify to enable intents before the example so you dont cause further confusion. You shouldnt really make a gist about many topics either for quality, Its poorly explained/explained and you always redirect the user for more info, maybe just make several gists that accompany the libraries documentation, the gist is quite large and its mostly resuming the official documentation over helping users understand it. You shouldnt criticize discord.py's server for not being beginner friendly as its stated, the library is advanced and its said in the server rules to first learn python over getting spoofed.
I swear i had it on, guess my client bugged or something
This is sort of within my domain as I'm the project lead for this stuff - I agree with most of your points, but I think we still need some quick way of pointing users in the right direction for the intents being required. Now that discord.py 2.0 is out, we get a lot of people with that question, because they're accustomed to 1.7.3 and as this is a basic error, their bot won't even start up. So instead of a guide like you mentioned, perhaps a !tag or similar?
Well then the gist should be a resumed version of the official documentation about migration from 1.7.3 to 2.0.0 and should accompony it by all means, over resuming the whole purpose of the library and its abstractions
Though doesn't discord.py have a migration guide? Usually they do, I'm not sure if they have one for this update yet since it's only been about a week
Maybe im confusing myself with some other memory, but i do remember a guide being available
If there is, there's no point in reinventing the wheel, we can just sort of summarize the important bits as a tag, and link the main part to the official docs
Yeah, i'm correct
How can i use this intents. I couldn't understand why my project doesn't run
See the screenshot Andy sent
in dpy 2.0 you need to use a setup_hook instead of on_ready right?
They don't have the same functionality
So one does not necessarily replace another
Hm okay
But it still not running
If you're talking about your commands not working, you need intents.message_content = True
I am trying to switch to from dpy 1.7.3 to just get slash commands, just trying to figure out what would be the easiest way without changing up too much of everything
I did, an error is still showing
Well you previously shouldn't have been doing anything in on_ready except maybe printing, so if you were doing what you were supposed to be doing, it shouldn't be that big of a switch in terms of using setup_hook
Knowing the error would be helpful
No it's not that
That was just a question
Just figuring out what's the easiest way as we need slash commands like very soon :0
Idk it's so long
I think fundamentally a lot of things are going to change and we as developers just need to get used to that. This is sort of a "revolutionary" period for discord developers since we've been practically neglected for the longest time. These are some of the biggest changes we've seen in a while, so there's going to be a lot of changes
More the merrier
I think it's because my bot's intents are disabled !
It's plausible
Yeah I understand, but I just unsure on what to do at this point
all fun and games until your list has 1k+ elements
Why 1k ?
Like what happens at 1k
Or condition will be larger uf
literally nothing, you would just have allot of conditions
the usage of in is more appropriate
I would suggest instead of constructing a list, you instead construct a set (if everything doesn't need to be ordered) Since a sets __contains__ (in) is O(1)
iirc its worse case is O(n) as well?
That will be very rare if you don't do anything weird to your elements
O(n) is only possible with hash clashing
Mhm
clash of hash
could someone help me please? im using easy_pil
async def rank(self, ctx, member:nextcord.Member=None):
if member is None:
member=ctx.author
async with self.bot.db.cursor() as cursor:
await cursor.execute('SELECT level FROM levels WHERE user = ? AND guild = ?',(member.id,ctx.guild.id))
level=await cursor.fetchone()
await cursor.execute('SELECT xp FROM levels WHERE user = ? AND guild = ?',(member.id,ctx.guild.id))
xp=await cursor.fetchone()
await cursor.execute('SELECT ssc FROM levels WHERE user = ? AND guild = ?',(member.id,ctx.guild.id))
ssc=await cursor.fetchone()
if not xp or not level or not ssc:
await cursor.execute('INSERT INTO levels (level, xp, ssc, user, guild) VALUES (?,?,?,?,?)',(0,0,0,member.id,ctx.guild.id))
await self.bot.commit()
try:
xp=xp[0]
level=level[0]
ssc=ssc[0]
except TypeError:
xp=0
level=0
ssc=0
user_data ={
'xp':xp,
'level':level,
'next_level_xp':100,
'percentage':xp,
'ssc':ssc,
}
background=Editor(Canvas((900,300),color='#ff6365'))
profile_picture=await load_image_async(str(member.avatar.url))
profile=Editor(profile_picture).resize(150,150).circle_image()
poppins=Font.poppins(size=40)
poppins_small=Font.poppins(size=30)
card_right_shape=[(600,0),(750,300),(900,300),(900,0)]
background.polygon(card_right_shape, color='#fd9fa1')
background.paste(profile,(30,30))
background.rectangle((30,220),width=650, height=40,color='#fd9fa1')
background.bar((30,220),max_width=650, height=40, color='#ffb4e7',percentage=user_data['percentage'],radius=20)
background.text((200,40),user_data['name'],font=poppins, color='#fd9fa1')
background.rectangle((200,100),width=350,height=2, fill='#fd9fa1')
background.text((200,130),f"Level - {user_data['level']} | XP - {user_data['xp']}/{user_data['next_level_xp']} | SSC - {user_data['ssc']}", font=poppins_small, color='#ff6365')
file=nextcord.File(fp=background.image_bytes,filename= 'levelcard.png')
await ctx.send(file=file)
the last 3 issues are not related to the channel
epic
huh
its a logging module, which i find redundant as logging is an stdlib and is quite simple
is it on pypi?
!pypi loguru
its a package
yeh for some reasons i have it but it just wont let me start my bot saying that the package is not found lol
how did you install it
try running just
python Bot/main.py
yeh in fact there are some commands that i did not change to / commands yet that's why it has a few errors
@cold sonnet oh im kinda new to poetry... maybe because i did not add the package to poetry.lock?
2022-08-22 21:52:55 INFO discord.client logging in using static token
2022-08-22 21:52:56 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 684d53e61f0910eca898f9d68ca27923).```
Whats server_welcoming.colours
it's for our server welcomer, to let u set the color embed u want
its a irrelevant error nothing special
I haven't used poetry yet, I don't see a reason to
what to do ?
Enable intents
already done
well in order to run the bot correctly you have to add the packages as far as i know
it's not an error, it's a warning and it's literally there
Is something not working?
my commands don't work
Enable message contents in the developer portal, then add this to your code:
intents = discord.Intents.default()
intents.message_content = True
# pass intents into your bot/client constructor
do all
Do u have on message?
no
for what reason?
thanks it worked
@sick birch do u know anything about poetry? how can i add a package to poetry.lock
π ofc u gonna do all if u enabled all
seems redundant to me especially having the presence intent on lmao
poetry add package_name
thanks
Should just be poetry add no?
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [β@everyone](mailto:'%40everyone)β role.
These roles are sorted by their position in the role hierarchy.
member.roles
oh i was right then
We all know what they meant
theyre still incorrect
Lmao
when will non slash command bots get executed
never
For bots above 70 guilds, Aug 31st. I believe, correct me if I'm wrong
unverified bots can still use the message content since it will be an unprivileged intent, while verified bots need to ask for the intent
but its recommended you use slash commands to avoid problems
which problems exactly?
good thing i said never to bots being executed kek
no info related to commands, prefix clashing and other horrible user experiences
oh
makes sense
i need to download discord.py from the main branch 4 slash commands?
no
It's on pypi
!pypi discord.py
You should be able to just install from pip
oke
value = data from db
fun():
using value
fun2()
using value
like for each time for value in fun1 and fun2 python intract with db or only once
????????????????????????????????????????????????????//
fun():
using data from db
fun2()
using data from db(same as above)
is both same ?
Well it depends on how you implement it
The way it should be done is you need to have a global pool from which you acquire connections
robin do u know why when i run my bot using poetry it will just say module not found?
can't tell wtf going on lol
I'm not nearly good enough with poetry to be able to answer that question, sorry
i really doubt thats related to poetry
π³ like can u give an example of good impimentation , and whats pool?
btw i have a globle connection
doing this the only thing i can think about is a poetry issue lol
thats odd, you used the add command right?
You should be good then
me?
yeah
it should be in poetry.lock and pyproject.toml
yep it's in both
have you checked the dependencies with poetry show package_name?
no no, your bots env
is it respond to reply with slash commands?
?
#bot-commands
well im not really sure
oh god π
what
hey guys, how do i get the guild's image?
@dry kelp i know your issue
do you?
you forgot to run poetry install lol
π
hahaπ
thanks a lot π
youre welcome lol
nah it's just that i was away to my grandma and i added poetry there.. nothing was updated on my pc haha
i just tried getting the code from github to keep working
thanks a lot bro istg
np
hi chat
Hi
how do i use cooldowns?
i've used like afew yrs ago ```py
@commands.cooldown(1, 5, commands.BucketType.user)
Thereβs should be a few examples on the GitHub page
a ok
how can i konw exituction time for a command ?
You mean the docstrings?
chad
you can compare the ctx.message.created_at attribute and the current timestamp, datetime.datetime.utc_now() for example, and the difference would be how long it took to execute
Ohh k k π€
!d discord.Message.created_at iirc it's utc, not local
property created_at```
The messageβs creation time in UTC.
you would need to compare to datetime.datetime.utc_now()
ooh good catch
how can i get members roles?
a specific member?
uh wait
i have to test my code first before i ask bcz this may work
ok my code works , but how can i get the guild's icon url?
property icon```
Returns the guildβs icon asset, if available.
property url```
Returns the underlying URL of the asset.
@bot.command(aliases=["f"], description='asd')
@commands.cooldown(1,1,commands.BucketType.user)
async def food(message):
id = str(message.author.id)
if id in data:
num = random.randint(1,3)
data[id]['inv']['food'] += num
await message.reply(f"You got {num}  from the bush.")
else:
await message.reply("You don't have a MooMoo account yet.")
@food.error
async def calis_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply("You are on cooldown, wait {e:.1f} seconds".format(e = error.retry_after))```
what does description on `@bot.command()` do?
pretty sure it just sets the help command description
i was accurate above ^
how can i use it on help command
does it have something that triggers it
or..?
its used in the default help command automatically
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [β@everyone](mailto:'%40everyone)β role.
These roles are sorted by their position in the role hierarchy.
lemme read my bots code
because the .status propery of author returns dnd, online, idle
!d discord.Member.activity
property activity```
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/latest/api.html#discord.Member.activities "discord.Member.activities").
ok sweet
link = links.find_one({})["link1"] ,, i want this a gobal veriable but facing error asyncio.Future' object is not subscriptable
should i insert it in a async funtion ?
with await
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
show code as well
you prolly wanna do
async def links():...``` and do `await link()...`
what's the links func?
its a data base collection
links = PAODdb['links']
PAODdb = get_database('discordPAOD')
its an instance of collection
link = links.find_one({})["link1"] find_one(...) returns a coroutine object which is NOT subscriptable, e.g you cannot do []
You have to use parenthesis to use subscript on the RETURN of the coroutine after awaiting
E.g ```py
(await some_coroutine(...))[...]
thats working but i want to get data from a globle veriable
just like color
in my code
so if change color , it will affect each and every command
ohh π€
Without using the parenthesis as a way to mark precedence it'll end up subscripting the coroutine then erroring
this will good right ?
No
now link have a data ?
You need to use the parenthesis like I showed
Otherwise there is no precedence for the return to be produced first
Then it'll error because the coroutine object isn't subscriptable
async def link():
return (await links.find_one({}))["link1"]
thissssssss
yes but probably better to extract it into it's own variable, couldn't hurt and only improves readability
oh k k
Is there some gradient generator from hex colors?
Lets say a person runs command -gen #fff #222 the bot gives him a gradient
Maybe using pillow
i wouldnt say its really needed as its quite reable as its just indexing a key to the value the coroutine returns, in my opinion making a variable seems quite redundant if it will stay unused
Its understandable to a certain level not to make a variable i would say
There is no noticeable difference using a redundant variable or not
I also inspected the garabage collector and it seems fine, there is really no incentive to use a variable or not
I would say if you are using coroutines though I'm gonna assume you know the very basics of python, which include using parenthesis for precedence
yeah i doubt their would be much of a difference to reference a pointer lol
Strictly speaking that wouldn't be a pointer, rather a reference
maybe im mixing my terminology, but when creating a variable it would make a point to a certain value which then the reference counter of the variable goes up to 1?
A pointer would point to a memory address where the memory for that object was allocated
A reference as the name suggests makes a reference to that object
A variable is just saying, I'm gonna be referencing to this other object that I was assigned too
If you wanted a "pointer" in python you'd use id for the address where the memory was allocated
!e ```py
print(id("foo"))
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
139678938100400
And the thing which you are referencing too is different from what I was talking about
Reference count is a different thing, but related to garbage collection in python
Yeah
Used to decide whether or not an object should be collected
Sorry for the awful wording that was my fault
Using id is very funny in python you can do some real cursed stuff
hi
!e ```py
from ctypes import *
class Foo:
def foo(self) -> None:
print("bar")
py_object.from_address(id(int) + int.basicsize).value = Foo
print(type(123))
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class ''>
like what creating segfaults on purpose, kek
!e ```py
import("ctypes").py_object.from_address(0).value = 0
@pliant gulch :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
one line segfault kek
Can be shorter, all you gotta do is make a pointer to un-allocated memory
thats literally a segfault, the accessing of an invalid/unallocated/restricted piece of memory and crashing the process
how can i make a reaction check expire after a valid reaction
I know π€
then why explain it you can always say you can make it shorter
I explained because I'm telling how easy it really is
To further say It can be shorten
thats fine
look at the logs
You'll know if you're being ratelimited
what version are you on? Are you using bot.run
yes
one of the latest d.py versions (https://github.com/Rapptz/discord.py@1fa7d7e40201b8a0eaee10a6b51786c60bc9d63f)
logs used to show ratelimited
just tried it with 0.5 seconds between bans and it doesn't pop up but still stopts at 42
How can I check the extension of a data i am getting from an API?
Like only the files with jpg, jpeg, png or gif should be visible, all the other stuff shouldnt come
not found
and why not from PyPI?
dpy2 isn't on pypi
it is
is it
Oh
was okimii online today
Anyways, for some reason if limit was 1 it would stop at 42
well when did that happen
I tried with like 1000 and it seems to work
is it not beta anymore
couple of days ago, iirc
damn I'm always late to know stuff
anyone know
There were rumors that it would've been last week. It was
okimii hasn't been online in 6 days π
Wtf happened
could've guessed it when I ran 2.0 on repl
probably irl stuff, it happens all the time
I was tryna talk to him
btw this somehow returns me duplicated bans (??
are they banned more than once
dm... u will get a reply eventually
yeah it's audit logs...
I did π
oh right lol
π³
await guild.bans()
returns you the bans
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
ok I had to make sure
Its old code but i think i didn't usr bans() because id didn't return things like author
@paper sluice since okimii is offline can I dm you?
I'm still not sure about it
Sounds like a job for the help channels
but I don't need help
I think you can do code reviews in the help channels
you can still ask for suggestions about code style or whatever there
How is it different?
well it works but it returns an AsyncIterator
Idk but I had a reason to use audit logs instead of bans
your dms are better though π₯Ί
i will come back tomorrow i guess its 2 am π
I don't mind, if you feel like it then sure
Apparently he has left discord sadly
no way
NO
source??
are you lying bro
He DMed me, gonna DM u both the screenshot
FUCK
I don't understand the correlation of personal issues and leaving discord
He just.... left, didn't even talk so yea, I wasn't able to do anything
this channel is dedicated to okimii now π
oh, a ban entry only has reason and user
tfw sad
Man rip okimiii
bad moment

to be asking
Oh rip, Robin yr DMs are closed
yeah i sent you an f req
gool ol robin
π
Cya
What do you have so far
Its giving all files,.even MP4 which aren't loading in the embed
How do I insert like, a custom ID for a button? I was doing this ```py
def init(self):
...
n = 0
for emoji, obj in objs.items():
object_button = Button(label=obj, style=ButtonStyle.primary, emoji=emoji, custom_id=str(n))
object_button.callback = self.object_button_callback
self.add_item(object_button)
n += 1
...
async def object_button_callback(self, interaction: Interaction, _button: Button):
# use _button.custom_id
...``` but _button became an unexpected argument, so I as I see I can only have interaction. Or is the only way to make a callback for each button?
async def check(reaction, user):
bal2 = await economy.find_one({"id" : user.id})
return reaction.message.id == msg.id and bal2['cash'] >=amount and str(reaction.emoji) == 'β
'
will async check work ?
any ristrection ?
if filename.endswith('.mp4'):
return```?
why would you need it async?
economy.find_one is corution fun.
oh, your db is async?
yes
welp you can use asyncio.run or asyncio.get_event_loop().run_until_coplete anyways
ohhhhhh got cha
I am actually using async praw which is related to reddit, and it the files doesn't end with .mp4 they just go to some other website
Check Content-Type response header
async def async_check(r, u):
...
def check(r, u):
return asyncio.get_event_loop().run_until_complete(async_check(r, u))```
got it
@vale wing u know?
get_event_loop I think it's deprecated, no?
no? well, since python 3.10 you need to create an event loop first (via new_event_loop), but that is still just a warning
In button callback the self is the button ig
ohhhh, right
Yes
no, callback is in the view
so self represents View
I am pretty sure the callback needs to be overridden in Button subclass, not in View
hm. maybe I need to subclass button...
Does View even have callback
Nope
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
See, you need to subclass Button
no, im not doing that π³
ok, I see
I was asking is that the only way, cus then I'll have 5 of them
that's why I was using for to add these buttons
whats the format for setting a command aliases in a Cog?
when i do @slvl.command((aliases["e","en"])) it says aliases is undefined
what is slvl
oh nevermind i figured it out, thank you thoughh
@commands.command(aliases = ["e","en"])
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: This event loop is already running
π₯²
well then just replace get_event_loop with new_event loop
oh wait no dont do that
new event loop for each reaction bruh
than how can i do that π₯²
not possible ?
*get_running_loop
oh? didn't know about that
how can i know everything about eventloops ?
dude wants know everything
!d asyncio.loop
No documentation found for the requested symbol.
hi
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
hi
Im getting a cat soon
congrats
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: This event loop is already running π₯²
cats are cute
What are you doing
get_running_loop
dont ignore TheMaster
he's better than me
Use asyncio.get_running_loop().run_until_complete(β¦)
Nah we are both python masters
welp, ok)
I am python not master
you are python?
I am corn snake
What is that
@torn sailthis same error
snake made out of corn
Show code
on new_event_loop Command raised an exception: RuntimeError: Cannot run the event loop while another loop is running
sure
Ok I didnβt find it but try replacing new_event_loop with get_running_loop
on new_event_loop -> Command raised an exception: RuntimeError: Cannot run the event loop while another loop is running
ohh ok
my mistake
wait a sec
Iβm not confident it will work tho
Command raised an exception: RuntimeError: This event loop is already running π₯²
Dang yeah I thought that would happen
maybe there's some other way than running async func in not async to do async check for wait_for..
Ok I think thereβs a good way but hereβs a bad way
coro = async_func()
try:
while True:
coro.send(None)
except StopIteration as e:
return e.value
Dang I should know this. Maybe try asking in #async-and-concurrency
π₯² tag me whenever u get ! , me also try to read about loops
How to call async function in sync function while an event loop is already running
two masters struggling at async problem
π
I would know this if it was concurrent.futures
But the problem with ur problem is that the check would block ur code
problem with the problem, ok
Dpy async checks when
2.2
wait, I don't think anyone here plays geometry dash
I played on friends phones
but you most likely don't know that 2.2 version for gd is been waited since 2017
I do not
Do geometry dash discord bot I dare yall
there is one
on geometry dash oficial server
Real
Can bots stream?
No
Aww
activity=streaming :lmao:
That's a shame indeed
You can make so many games that way cause live screen
Yeah AI playing some game and streaming to VC would be very popular
there is a pokemon fully remade in minecraft
do you think something is not possible in discord?
In minecraft they remake literal 8-bit CPUs
whats pre-invoke command check ?
A check that decides whether to run the command or not
ohh k uf
@bot.command()
async def c(ctx, arg:str):
if ctx.channel.id!=1011497323815239770:
cchannel=discord.Embed(title=f"``{ctx.message.content}`` has been used in a invalid channel",description="Please try again ! [#1011497323815239770](/guild/267624335836053506/channel/1011497323815239770/)",color=0xffff00)
await ctx.send(embed=cchannel)
return
await ctx.reply(f"disc.gg/{arg}")
its not sending it at all.
spacessss
ive checked over the code and im not sure what the issue is since it runs fine
It runs fine its not identation.
not sending what?
that is indentation
Yo can u send an ss of that code block
Iβm on phone so itβs hard to read
its fine hol up
he's just trying to send a message after return
return
await ctx.reply
Yeah I wasnβt sure if that was discord mobile having shitty code blocks or an indentation problem
Add await interaction.response.defer() in the button callbacks
@bot.command()
async def c(ctx, arg:str):
if ctx.channel.id!=1011497323815239770:
cchannel=discord.Embed(title=f"``{ctx.message.content}`` has been used in a invalid channel",description="Please try again ! [#1011497323815239770](/guild/267624335836053506/channel/1011497323815239770/)",color=0xffff00)
await ctx.send(embed=cchannel)
return
await ctx.reply(f"disc.gg/{arg}")β
Still doesnt work
what are u trying to do? there's many errors here
@winged dock
yeah
Yup
Its a vanity checker i made thats it
You just type !c then the vanity u wanna check
doesnt break terms and its obv not malicious
``def runGiveTokens(amount: int):
if amount % 1 != 0:
amount += 1
tokens = get_all_tokens("tokens.txt")
all_data = []
tokens_checked = 0
actually_valid = 0
give_token = 0
for token in tokens:
s, headers = get_headers(token)
profile = validate_token(s, headers)
tokens_checked += 1
if profile != False:
actually_valid += 1
data_piece = [s, token, headers, profile]
all_data.append(data_piece)
print(f"{Fore.GREEN} > {Fore.WHITE}{profile}")
else:
pass
for data in all_data:
lines = 0
s, token, headers, profile = get_items(data)
if give_token >= amount:
with open('tokens.txt') as f:
for line in f:
lines += 1
contents = f.readlines(amount)
removeToken(token)
makeUsed(token)
@bot.slash_command(guild_ids=[settings["guildID"]], name="givetoken",
description="Allows you to give tokens to an buyer.")
async def token(ctx: discord.ApplicationContext,
amount: discord.Option(int, "Number of tokens to give.", required=True)):
if not isAdmin(ctx):
return await ctx.respond("Only Bot Admins can use this command.")
if isAdmin(ctx):
await ctx.respond("Started, this could take a while.")
runGiveToken(amount)
return await ctx.edit(f"{contents}")``
I want to make an command with
/givetokens (AMOUNT) And then he send the amount of tokens from an txt file
But it does not work
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
It doesn't work because of your naming conventions 100%
How do I save my previous data when the bot is shut down and bring it back the next time the bot is turned on?
cache?
No π
"ratings": [
{
"source": "Internet Movie Database",
"value": "7.9/10"
},
{
"source": "Rotten Tomatoes",
"value": "94%"
},
{
"source": "Metacritic",
"value": "79/100"
}
]
this is a part of an api and i want to get all three of them, ik how to get first one but have 0 idea about the next two
lst = [f"{i['source']}\n{i['value']}" for i in data["ratings"]]
um hi i coded a Dm command thing in by bot and i wanted it to delete the message that the bot sends as a successful dm that is like Dm has beeen sent
@bot.command()
@has_permissions(administrator=True)
async def sendDm(ctx, member: discord.Member, message):
userDm = await member.create_dm()
await ctx.send(embed=discord.Embed(
description=f"** :tick: DM has been sent to {member.display_name}**",
color=0xffff00))
await userDm.send(message)
await asyncio.sleep(5)
await message.delete(message)```
File "main.py", line 23, in sendDm
await message.delete(message)
AttributeError: 'str' object has no attribute 'delete
can someone help me please
I guess ctx.message.delete()
delete_after exists
o
The cmd author?
the message that the bot sent
well anyways delete_after is for that
await ctx.send(embed=myCoolEmbed, delete_after=5)``` will delete the message after 5 seconds @west veldt
omg tysm
btw, What font are you using?
By the way, you'd better use slash commands if this bot is not going to be private @west veldt
oh
ill try those
because message content is becoming priveleged since august 31
@bot.command()
@has_permissions(administrator=True)
async def sendDm(ctx, member: discord.Member, message):
userDm = await member.create_dm()
await ctx.send(embed=discord.Embed(
description=f"** https://cdn.discordapp.com/emojis/1007931312096686140.webp?size=48&quality=lossless DM has been sent to {member.display_name}**",
color=0xffff00 , delete_after = 5))
β
is it good??
what do you want me to rate?
no no no
Doesn't follow pep8 2/10
then what do you want me to say
Can you please use the proper format to send code @west veldt
ret = await coro(*args, **kwargs)
File "main.py", line 18, in sendDm
await ctx.send(embed=discord.Embed(
TypeError: __init__() got an unexpected keyword argument 'delete_after'```
you put delete_after inside the embed
check closing brackets
await ctx.send(embed=Embed(..., delete_after=5))```
it should be outside, to be a kwarg of send
Another way to do delete is to send the message as a variable and do βmy message.delete(delay=5)β
bruh why
Iβm in mobile so I have a valid excuse for my bad format
Coz then you can edit it if you want π
It doesnβt matter which way he uses. Both are valid
Your way isnβt the only way
πΏ
Both are valid indeed but first requires one line of code and second requires 2. Less lines more readability in this case

bruh it messed up with my purge command File "main.py", line 30, in purge await ctx. channel. purge(limit=amount + 1 , delete_after = 10) TypeError: purge() got an unexpected keyword argument 'delete_after
Why do something that can be done with a kwarg with additional statement
Kwarg already does that
Less lines is not always easier to read. There are examples online where less does not always mean better.
And in this case an extra line does not matter much
how do you think are you gonna delete purge?
it's deleting a message
and you are doing it in purge
@bot.command()
@has_permissions(administrator=True, manage_messages=True)
async def purge(ctx, amount=5):
await ctx. channel. purge(limit=amount + 1 , delete_after = 10)
await ctx.send(embed=discord.Embed(description=f":tick: successfully deleted {amount} messages in {ctx.channel}", color=0x2E08CB))```
i didnt even used delete_after here
oh wait
if you want to delete the sent message why would you put it in purge
i get it
Make this a slash command π
i will today
Woo
slashpurge 10
To delete a message with your method you would also need to declare a variable and you can avoid it with our method, another disadvantage of yours
Not that much different to a regular conmand when programming
interaction instead of ctx
yes
app_commands instead of ext.commands
And @strange knoll_command instead of bot
So what type of discord bot you hoping to make?
wth why you write ctx.channel.purge with spaces
Nothing wrong with having a little bit of space
PEP 8 is a thing
a little bit of space:
play_again = Button ( label = "Play again" , style = ButtonStyle . primary , emoji = 'π' )
ahah
Pepper pig can go sit in a corner. If it makes it easier for him to read he can use it. As long as it works it is all that matters
he can read and understand it now, not in 2 weeks
Relax. He is clearly inexperienced. He is probably not doing this professionally yet and just wants to learn the basics. He can learn about pepper pig another time
I'm relaxed lmao, it's a suggestion
A little bit of space is not an issue if the code works and can be read
You attacked him
where
A suggestion or helpful comment would be βhey you donβt need spaces in your variablesβ and perhaps provide an example
good morning mr Master32
why you're making a fuss
Youβre the one bring pepper pig into this
Code should also be understandable for others, that's very important in programming. And if everyone follow some guide of code looking like PEP 8
Like.. try to read thispy try: e = Embed ( title = "Cat" , color = Colors . random () , timestamp = ctx . message . created_at ) e . set_author ( name = ctx . author , icon_url = ctx . author . display_avatar . url ) e . set_image ( url = await self . bot . alex_api . cats () )
morning
Wait. βE . Set_authorβ works?
imagine
With the spaces
yes
Awesome
if it works then it's ok π
Today I learned
yeah. no prob
π
Better to accustom yourself to follow guidelines rather than to rewrite 6k lines of code trust me, if some issues can be fixed by the formatters, like bad spaces or smth, the names can't be
b = int ( cat )
pigman = str ( yo_mama )```
it works!!
No wayy
?
would be fun to rewrite 6k lines just to rename variables names, "as long it works it's ok"
If I was home Iβd be editing some code just to annoy the anti-space people
I have done that thing once and don't want to do it again
I'm sorry for you π
6 seems more than meaner 1.2k project π¦
Stupid phone
Fuck it autocorrects runs me life now
Whatever it puts is whatever I says
alright, I got my RPS to work, but it says application failed each time and thinks like trash, cus it says that it's a draw when I chose rock and he chose paper
I remember making RPS too for bobux bot
skill issue issue skill
lmao
Hopefully I will be able to bring the bobux back to life one day
It was such a nice bot π©
But message content intent ruined it
alright, i fixed interaction failed thing with deferring
but it still thinks that 2 +2 = 5
F
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Won't this send it to the sender instead of the user cited in the argument?
use the user object to send
@bot.command()
async def send(ctx: commands.Context, user: discord.Member):
await user.send('hello')
user object?
waht?
btw @shrewd apex do you know who's that
I'm new to Python and programming generally . So I might sound dumb when I ask this:
ctx: commands.Context What does this bit do?
now every time i open pycharm i feel so lethargic coz the part of bot left to do is embed designing it's such a chore
lol
it's a typehint
it doesn't do anything
it does
python doesn't enforce type checking during runtime
it's only helpful for linting that's it
well not at runtime yeah
disnake.ext.commands.errors.ExtensionFailed: Extension 'Cogs.Fun' raised an error: TypeError: <class 'disnake.ext.commands.context.Context'> is not a valid parameter annotation
ξΊ§
I kept getting this error
code?
@commands.slash_command(name="dm",
description="DMs target user with *Message*",
dm_permission=True)
@commands.has_permissions(administrator=True)
async def dm(self, ctx: commands.Context, user: disnake.Member, message: str):
try:
await ctx.user.send(message)
await message.channel(f"DM sent to {user.name}")
except:
await ctx.channel.send(f"It's not working. :Sad: this msg did not send: ({message}) to {user.name}")
Here it is
Been having this error since yestrday lol
wym?
slash commands give disnake.Interaction
Ohhhh.. So I should replace ctx with inter?

well you can name it anything you want but yeah inter is better, and typehint it with dinake.Interaction
Alright. lemme try
Lemme first learn about typehint lol. That's the first I've heard of it 
!typehint
Type Hints
A type hint indicates what type a variable is expected to be.
def add(a: int, b: int) -> int:
return a + b
The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.
It's important to note these are just hints and are not enforced at runtime.
add("hello ", "world")
The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.
Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.
mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.
bruh no
then do channel.send
that works too i though he was using a custom channel or something
no
idk my head not working today i was awake all night studying maths π
my parents care ;-;
mine too
I'll keep all these in mind guys. Thx 
kek well anyway i did good in test hopefully full i think i did get it all right
π₯asher is a genius
i wish u more genius than me
yes
everyone here is a genius
how is ur day going π long time no talk
by the way, @slate swan do you know what happened to okimii?
ask hunter
he gonna know for sure
lol am at my uncle's so kinda busy these days
nood said he's not coming back online
yes
what?
π
i wish i could go to my relatives house as well but we are like literally on opposites of the country
sarth keeping us in suspense 
burh
I want to know what happened to oki
if someone did something with him im gonna get the revengest revenge on that guy
yeah most likely
...
@slate swan @slate swan
how to make my bot count propetly
why is he thinling rock vs scissors is a loss
he Dumbass
send the bot to school
ok
kek pack it away and send it to school it wasn't even a question
no opinion required 
...
i think he's too stupid to understand
bruh...
I don't wanna learn JS just to rewrite this dumbass
await guild.me.edit(nick="Always Stopping Take Me Down")
π
idk, put it wherever you want, that's just how you change nickname
even bot protests for our education measurements
lmao
ModuleNotFoundError: No module named 'google'
what is that how to fix it?
you are trying to import google which does not exist
!pypi google
you need to install it
ye i do but still have error
File "c:\Users\asdro\OneDrive\Desktop\rustJun\rustplus-master\main.py", line 8, in <module>
from rustplus import RustSocket
File "c:\Users\asdro\OneDrive\Desktop\rustJun\rustplus-master\rustplus\__init__.py", line 7, in <module>
from .api.remote.fcm_listener import FCMListener
File "c:\Users\asdro\OneDrive\Desktop\rustJun\rustplus-master\rustplus\api\remote\fcm_listener.py", line 1, in <module>
from push_receiver import PushReceiver
File "C:\Users\asdro\AppData\Roaming\Python\Python38\site-packages\push_receiver\__init__.py", line 1, in <module>
from .push_receiver import *
File "C:\Users\asdro\AppData\Roaming\Python\Python38\site-packages\push_receiver\push_receiver.py", line 11, in <module>
from .mcs_pb2 import *
File "C:\Users\asdro\AppData\Roaming\Python\Python38\site-packages\push_receiver\mcs_pb2.py", line 33, in <module>
_descriptor.EnumValueDescriptor(
File "C:\Users\asdro\AppData\Roaming\Python\Python38\site-packages\google\protobuf\descriptor.py", line 755, in __new__
_message.Message._CheckCalledFromGeneratedFile()
TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
1. Downgrade the protobuf package to 3.20.x or lower.
2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).
More information: https://developers.google.com/protocol-buffers/docs/news/2022-05-06#python-updates```
did you check the link?
Using guild.audit_logs() to get bans, how could I know if the ban is still active?
Trying to avoid using bans() because it gives too little info
Oh I could check if the ban from audit logs is in bans()
hm, I thought you can check if the user of AuditLogEntry is banned
but I can't find anything to check if the member is banned or not
I guess I'll try this
and ban entry also doesn't provide any .extra stuff
Does anyone have expierence with vps that could help me? its about my bot so its dpy related
so I guess this is the right way
check this channel threads
Yeah I know
does anybody know a bot that can create a one time use invite rather than having to do it manually
This is a python related channel, Iβm sure you can get your answer on Google
Where is okmi
same question
left discord apparently, seems to have deleted his github acc as well
Google must have an answer on your question :lmao:
do you know why?
sarth and noid say they know, but don't tell me(
no, hunter probably does, you can ask him
@maiden fable why okimii left?
Not related to discord bot development though
This is the python discord server sir
from colorama import Fore, Style
import time
import time
tokem="ok"
bot = commands.Bot(command_prefix='!',
intents=discord.Intents.all())
@bot.command()
async def clear(ctx):
await ctx.send("Clearing all channels...")
time.sleep(0.9)
guild = ctx.guild
for channel in guild.channels:
try:
await channel.delete()
bot.run(token)
someone tell me why the last line shows errors?
ik its not that
so spotable
then what is the error?
what's the error
bot.run(token)
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Please provide the full traceback for your exception in order to help us identify your issue.
Hello, I want to do a button within a command, but how should i do it because i dont want to make an extra class for it.
Line 20 bot.run(token) unexpected unindent
@silk fulcrum
can you send full traceback? @winged dock
is this the right code?
cus error says 18
bot.run shouldnt be indented
it's unexpected unindent π³
have you ever seen that before?
what's your code?
from colorama import Fore, Style
import time
token="here"
bot = commands.Bot(command_prefix='!',
intents=discord.Intents.all())
@bot.command()
async def clear(ctx):
await ctx.send("Clearing all channels...")
time.sleep(0.9)
guild = ctx.guild
for channel in guild.channels:
try:
await channel.delete()
bot.run(token)
what the heck, it just changed
Ik
try cannot be alone
ohhh right
You need a try combined with an except or a finally
and please consider following PEP 8
alr
and also use asyncio.sleep instead of time.sleep
where is your exception?
Ive fixed it
Gonna share something with you in DMs
ok
π€
can i see it as well 
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
Hunter being overloaded
blockingio
File "main.py", line 63, in <module>
WinterFeedback.run ("----")
File "/home/runner/FeedBacksBot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/FeedBacksBot/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/FeedBacksBot/venv/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/home/runner/FeedBacksBot/venv/lib/python3.8/site-packages/discord/client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
[2022-08-23 14:00:06] [ERROR ] discord.client: Ignoring exception in on_guild_channel_create
2022-08-23T14:00:06.289457+00:00 app[worker.1]: Traceback (most recent call last):
2022-08-23T14:00:06.289464+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
2022-08-23T14:00:06.289465+00:00 app[worker.1]: await coro(*args, **kwargs)
2022-08-23T14:00:06.289466+00:00 app[worker.1]: File "/app/cogs/antievents.py", line 73, in on_guild_channel_create
2022-08-23T14:00:06.289466+00:00 app[worker.1]: await channel.send(embed=embed)
2022-08-23T14:00:06.289467+00:00 app[worker.1]: AttributeError: 'Int64' object has no attribute 'send'
what does this mean?
enable ur intents
no code no help, channel is probably a number here
channel = db.find_one({ "guild_id": channel.guild.id })['anti-log-channel']
if punishment == 'ban':
punishment == "Banned"
if punishment == 'kick':
punishment == "Kicked"
if channel == None:
pass
else:
log_channel = self.bot.get_channel(channel)
embed = discord.Embed(color=col)
embed.description = 'Stylus Anti-Nuke Protection Logging'
embed.add_field(name='Banned User', value=f'{i.user.mention} - **{i.user.id}**', inline=False)
embed.add_field(name='Reason Why', value=f'Creating Channels Without Whitelist', inline=False)
embed.add_field(name='Action Taken', value="The User Was {punishment} Immediately", inline=False)
await channel.send(embed=embed)
[2022-08-23 14:00:06] [ERROR ] discord.client: Ignoring exception in on_guild_channel_create
2022-08-23T14:00:06.289457+00:00 app[worker.1]: Traceback (most recent call last):
2022-08-23T14:00:06.289464+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
2022-08-23T14:00:06.289465+00:00 app[worker.1]: await coro(*args, **kwargs)
2022-08-23T14:00:06.289466+00:00 app[worker.1]: File "/app/cogs/antievents.py", line 73, in on_guild_channel_create
2022-08-23T14:00:06.289466+00:00 app[worker.1]: await channel.send(embed=embed)
2022-08-23T14:00:06.289467+00:00 app[worker.1]: AttributeError: 'Int64' object has no attribute 'send'
what does this mean?
probably db.find_one(...) is returning an object, try to print channel
also you should use an asynchronous library for your database
Is there a way to disable invites/ remove the invite link for my bot?
you can make your bot private
will it still remain on the servers that it's on?
public param
what
no clue
when does that appear?
when I
toggle that
When trying to turn off the 'Public Bot' toggle in the developer portal for a bot, this error message is displayed:
"Cannot have install fields on a private application."
The actual error is that the bot cannot be private unless the OAuth2 Default Authorization Link is set to 'None'. The current error message is not sufficiently clear enough to diagnose the problem and I was forced to find the solution through a Reddit post.
Please consider revising the error message to "Bot cannot be set to private with current Default Authorisation Link settings." or something similar.
Please also consider revising the location of the error message and move the error message to appear near the associated toggle the error is for in accordance with relevant UX design heuristics.
ah
uhm... isn't everything explained?
How do I calculate how much ram my bot needs?
len(bot.guilds)
no I meant, its in 230 servers
damn
does it makes a difference?
You could measure it using the psutil library
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
@heady citrus
channel is probably a number here
and a number does not have a .send method
you need to fetch/get the channel object and use send on it
Yes, he has channel ids stored in a database
He fetches the channel, just calls .send to the wrong variable
log_channel is the variable with the channel
log_channel.send() is right
yoo
does anyone have the code for how to change time zone?
the bot shows in UTC
but i want to change the time zone
@glad cradle or @silk fulcrum
u guys know?
wow, pinging concrete people
π
well... I guess just change the timezone? I don't understand where do you want it to change timezone without the code or further explanation.
umm i wanna change in the bot
like the bot displays utc time only
Doesnβt discord change the time zone anyway with the special time thing
yes the best on this channel π
embed.add_field(name="Created Account On:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined Server On:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
code
no 3:27 am
not using time tags π

