#discord-bots
1 messages · Page 536 of 1
thank you lmfao
forgot a > lol
i wasnt trying to give him that so he would figure it out himself but jesus
he really put User_Id
everyone starts somewhere tho
lol 1st week of py
yeah ig
atleast i didnt start out like a skid 🙏
do you at least know basic python?? hoping so
i started out discord.py with no experience at all
somewhat lol
coding aint my thang but networking is
all you boss man
should i put a set.author() on it so it doesn't look so plain
it would maybe look nice try it
eh
idk i personally hate working w embeds
i only use embeds for things that hold data thag doesn't look good in a normal message
yeah
@pliant gulch
?
lefi looking clean
Thanks that's what I was really going for
Currently working on lefi's command extensions right now
yeah, do you have embeds implemented?
Yes
dope
Yep, It should be just likes discord.py's
We have documentation as well, although not sure how readable they are since I wrote them https://lefi.readthedocs.io/en/latest/API-Reference/embed/?h=embed#lefi.objects.embed.embed.Embed
ooh allright
and sending them is also just like dpy?
Yes you need a channel object which has a send method which you then pass the embed object to the embeds kwarg
Keep in mind currently since the discord API has deprecated embed, the single embed field I only have embeds kwarg set
Meaning a slight change as in await Channel.send(embeds=[embed])
In the future I will change this to not require passing a list
oh allright thanks
I would also highly suggest if you plan on using the wrapper to install it via poetry
As I don't have a setup.py for dev dependencies, so if you use pip you will be forced to install every dev dependency I use
Yea, I will have to change that later
ive never heard of poetry
how will pip react if i install the same package via poetry
Uh well poetry is a venv
So its seperate from your global packages
You just setup your poetry venv, do poetry add <package>
Then everytime when you want to run stuff you need to do it from poetry, as again its a venv
oh i see
But if you do install the wrapper with poetry use the --no-dev flag to get rid of installing any dev dependencies
This will make it so it only installs the two packages I require for the wrapper
aiohttp and pynacl
i see allright
How am I able to make use of a button more than once
Meaning it can be clicked multiple times
button?
Yes
lmao discord has been adding new shit every day
dont know if i did it wrong but e = lefi.embed(set_title="No Cursing") TypeError: 'module' object is not callable
Been out for a little, I just never used them
Embed
embed is the file
Ignoring exception in command join:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/1stDiscordBot/music.py", line 15, in join
voice_channel = ctx.author.voice.voice_channel
AttributeError: 'NoneType' object has no attribute 'voice_channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'voice_channel'
Ignoring exception in command join:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/1stDiscordBot/music.py", line 15, in join
voice_channel = ctx.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'voice_channel'
You aren't supposed to be passing set_title as well
its just title?
Its a method, should be lefi.Embed.set_title(...)
im tryna get discord bot to join vc but it errors
ahh that makes much more sense
Err no no I'm sorry
@client.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
I don't even know my own wrapper nah, but for titles its just the kwarg
this is code
first, summarize the error man
some of your docs like the Client one is good
the lower ones are not so descriptive
and hella confusing
I did almost all the base stuff you see in lefi
my collaborator blanket did some other stuff
such as some http methods, embeds, flags and enums
👍
ctx.author.voice.voice_channel
nvm i found my stupid mistake
hows the commands going
Commands, String Parser, Context, Corresponding events, and handlers are done
Heres the flowchart I'm following for release if your interested
Checks as well
already saw that in the githuyb
https://github.com/an-dyy/Lefi/pull/5 Heres the pull request where I'm actually doing all the command stuff, more accurately its on the ext branch although
i see
well ill star it
thanks ❤️
im making a very simple register command that only adds a role, changes the nick and that if it's successful it'll add a simple checkmark to the "!register ..." message and if the nickname already exists it'll add a cross to the message and it'll send a message to the author with a certain message
and i can't seem to figure out how to do it
whats the reason behind having a unique nickname
it's for a certain gamemode/competitive thing
you are going to need to compare every nickname, so store it
yeah but i need it to be only possible with one name cus it's for a mc gamemode
as i just said
still storing?
well i dont suppose you wont to loop through every members display_name
so best way is via database or just a json file will do fine?
json is not a db
a json is not a db.
sqlite3 is good for small bots. if you like using dicts then you can use mongo db
i know json isn't a db, but would json be good enough for storing such simple things or is it better to use sqlite3 for it, to prevent data leaks
storing data in a json is astronomically bad practise
yeah alr so sqlite3 is the way then
if you wish. sql takes 10 mins of reading to learn. mongo is very easy also and who doesnt like working with dicts
yeah i already know sql so i'll be fine with that
bottom line is it should never be used a a database
static data, sure, but dynamically changing data inside a json is a big no no
I made a user info command a while back and it works well but whenever I do the command it shows this for the user badges and this is my current code https://hastebin.com/qitecusala.csharp
How do I get rid of the [<Userflags.?
add [12:] before .title() to remove the first 12 characters from the string
possibly a better way to do this but im guessing this will work just as well
@slate swan
if int(details["level"]) in levelupdict.keys() and not message.author.bot:
im checking that the users level is in the dict values. if not then pass, when the users level is not in the dict is errors nonetype and since its on_message it literally clogs up my terminal. anyway to not do that? lmao
It worked
One more thing cuz when a user doesn’t have any badges it shows this, how would I make it so it shows N/A instead?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Hey guys I'm hoping someone can point me in the right direction as to what I will need to accomplish this. I'm very new to coding but I need to get out of following tutorials and actually start doing something.
I want to code a bot for my discord server. The bot should allow users to upload pics to the bot via discord and via commands, the pic will show.
In our Minecraft server, players have Plots so for example
[]Plot @vapid ingot
Displays a gallery of screenshots uploaded by Abdul
im guessing these screenshots are stored on the minecraft api?
I have zero clue
If someone can help me come up with some sort of structure that would be great
you arent giving us any idea what you are trying to do
where are these images coming from
so pictures to minecraft blocks?
read the error
read the error
There is no error
^
whats the red thing then?
Kayle, it won't give you an error in ur console or whatever
What's the issue due to?
read the ephemeral message
Read
yes
didn't say anything related to the console
in the ephemeral message..?
nope.
How to solve the problem
did u try googling the error
Can you show your code?
Is it possible for them to come from discord?
Would I need to upload them personally?
@dapper cobalt hey been testing out dislash. what is the attribute to be able to grab the interaction user
i tried interaction.user.mention but that isnt a thing
interaction.author iirc.
no attribute author
Show me your code.
name="truth",
description="Sends a random truth"
)
async def truth(
inter: disnake.ApplicationCommandInteraction,
rating = Param(
description="The Rating of which you want the question to be")
):
if rating == None:
r = requests.get(f"https://api.truthordarebot.xyz/api/truth/?rating=")
res = r.json()
Tile = f"Here is a truth for you"
Desc = res['question']
embed=discord.Embed(title=Tile, description=Desc, color=bot_embed_color)
await inter.response.send_message(embed=embed)
else:
try:
r = requests.get(f"https://api.truthordarebot.xyz/api/truth/?rating={rating}")
res = r.json()
Tile = f"Here is a {rating} rated question for you"
Desc = res['question']
embed=discord.Embed(title=Tile, description=Desc, color=bot_embed_color)
await inter.response.send_message(embed=embed)
except:
await inter.response.send_message("Please send a valid rating!! Valid parameters are `pg`,`pg13`,`r`")```
Sorry for late reply I got a call
Try await inter.reply instead of await inter.response.send_message.
It won't work
Why not?
Wrong Syntax
Pass inter without disnake.ApplicationCommandInteraction.
Won't work again it's a slash command
follow python naming conventions
That's not the error tho
@inter_client.slash_command(description="Test command")
async def test(inter):
await inter.reply("Test")
It's an example from the documentation.
I am using disnake tho
Ah, disnake not dislash.
Yup
this just prints the property
Because what is discord.Member?
Which discord.Member?
i didnt define it
it doesnt come
!d discord user.avatar.url
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
i dont know how you get the member that interacted
kk
I can't tell you "ride the car" without telling you which car.
You can't tell it to mention a member without telling it which member.
i dont know how you get the member that interacted
invalid syntax
Show your code.
@client.command()
async def test(ctx, member:discord.Member):
member_avatar = member.avatar_url_as(*, format=None, static_format='webp', size=1024)```
Pass inter and not ctx.
Just member.avatar_url.
u dont need *
or format=None
Are you using discord.py 2.0?
3 what?
3.0?
ye
what the
That's not even a thing..
theres no 3.0 version tho
not even the main dpy or any other forks are 3.0 not to my knowledge
print(discord.__version__) and see what version are you using.
k
or pip freeze
🤨
it gives nothing
Did u print it?
ye
and there was no output..?
yeah....
well you must've did something wrong
well how do I update my version
show me a ss of what u did
it says module discord has no attribute version
hm
version or __version__?
Anyways, try member.avatar.url and see.
k
k
str object has no attribute url
member.avatar.url is a thing only in 2.0+
if you are using the pypi version (<=1.7.3) it would be member.avatar_url
command async def name(ctx, argument)
So argument would be something going after the command right?
yeah
!name text , here text would be the argument
ctx is Context object
how could i use text as mentioned user and for example return his avatar url
would it be
ctx.send(arg.avatar.url)
or what
depending upon the argument name , its argument.avatar_url if you have installed discord.py's pypi version
context.author.avatar_url
not the author
no.
async def command(ctx , user):
``` in this case it would be `user.avatar_url`
take it as an example
yeah thanks!
Command raised an exception: AttributeError: 'str' object has no attribute 'avatar_url'
Yeah it works hella yeah thanks
so what is the difference on
user = discord.User()
user : discord.User
or the first one wouldnt work
() means you're calling a function - discord.User is a class that contains functions
= discord.User means assigning it as discord.User
: discord.User means the argument recieves a discord.User object
thanks
how to get the url from attachment?
it says message.attachments list has no url
it returns this
<Attachment id=898427555231698964 filename='90674364_p0.jpg' url=
'any url'
how to get only url
[url]?
The attachment URL. If the message this attachment was attached to is deleted, then this will 404.
what about every single attachment
loop through them py for attachment in message.attachments: #do something
what if i want to send them all in one message then?
make a list and then append the urls , join the list using .join function and send it
oh
Is there any argument for the user who deleted message? for example admin deleted someones message can i have somehow his user id
the admin or the author of the message
you can't get an id of a user who deleted the message except using the audit log action thingy
hi can someone list some forks of discord.py?
disnake, enhanced-discord.py, pycord
nextcord, hikari
how to reference message that bot just have sent?
hikari aint a fork , just saying
assign a variable for the message
message = await ctx.send(......
``` and message would be the message reference
hey im getting the "bad token passed" error and ive tried literally everything i know to try to fix it and it even worked in a scratch python file i made.
srry to interrupt lol
make sure the token is correct , try regenerating it and using a new one ,
Make sure its a string
i made sure it was a string and i regenerated it 3 times and i also tried to switch it out for the client secret and the client id
ill send a snippet
try:
prefix.run(os.getenv('TOKEN'))
except discord.errors.LoginFailure as a:
print("Meech has Tripped and Fell because a Bad Token was passed")
and ive tried it outside the try: as well it didnt seem to matter
is your .env file something like env TOKEN = "THE TOKEN"
nah i was using replits "secrets" feature
oh
ill try it rn
nah , it wont be supported by replit
rlly?!
try removing the " once from your secret
it redirects you to the secrets tabs
just tried this but it doesnt seem like it worked
could it possibly be anything with the internet?
this is how you should enter the token ( dw its invalid token)
nope
i was askin bc ive made another small test file using the same token and it worked fine
wdym?
ive tried removing the quotations from my "secret" value
its already a string
dumb question , but did you save it?
i did this token = os.environ['KEY'] then did bot.run(token)
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
hm
i just used the tutorial
alright @slender river you will be using os.getenvb('TOKEN')
since replit is based on linux systems
are ur presence intents on?
then idk, they work for my bot, and so did kayle's example for his bot, so must be some issue on your end
try printing the member's activity
see if that returns you anything
im a boy though
i clearly says "his"
lol
yeah 💀 replit saves automatically very often
ive tried this before but ill try it again maybe i did it wrong
code?
AHHHH
that sounds like itll work
ill try it rn
spot.color is a tuple
change it to something else
and spot is a variable for the activity
i dont think activities have colors
it technically didnt work but it didnt give me the exact same error so its progress
but you should loop over its elements so that you don't do the same code again and again until you find the index which has the spotify activity
Traceback (most recent call last):
File "main.py", line 109, in <module>
prefix.run(os.getenvb('TOKEN'))
File "/usr/lib/python3.8/os.py", line 792, in getenvb
return environb.get(key, default)
File "/usr/lib/python3.8/_collections_abc.py", line 660, in get
return self[key]
File "/usr/lib/python3.8/os.py", line 672, in __getitem__
value = self._data[self.encodekey(key)]
File "/usr/lib/python3.8/os.py", line 778, in _check_bytes
raise TypeError("bytes expected, not %s" % type(value).__name__)
TypeError: bytes expected, not str
also the way you defined your spot here returns a tuple of a generator object and None
for activity in user.activities:
if isinstance(activity, discord.Spotify):
... # Means that it found the activity so here add your code to send to the channel
return # Return so it doesn't also send the next line of code
await ctx.send('No spotify activity detected')
utils.find is also a great way to avoid iterating trough the activities.
spotify = discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities)
if spotify:
...
else:
...
or that ^
also yk that iterates over it as well right?
yeah, but iterates lib side, which (in my opinion) looks better lol
it's really not 😂
that's new
is it? fuck
😂

if you're not using 2.0 you can do this instead
f"https://open.spotify.com/track/{activity.track_id}"
it is?
like who shared the song?
no clue what that is ngl
1 sec lemme check the spotify docs lol
i made my spotify command back in january or so
no clue what that ?si=... is but it works 😂
nope
it isnt unique to you - its different on every song
but i hard-coded that 🤔
no clue why 😂
So recently Spotify added a "?si=" parameter to song when you copy the url. This apparently gives the url a unique stamp in where it was copied and by who. This is seemingly due to new EU regulations.
😳 😳
Can a bot with discord.py show a YouTube video for example?
bots cannot screen-share.
Ok
oh 😳
yeah better remove that 😳
yes
can someone help me i cant host my bot on heroko
what will be the output of it?
print(''.join(map(lambda x:chr(x),[115 if i==int(False) else ((((int(True*2) * 50)-5)+25)-5)+int(True>>False) if i==int(4*6-8+459-74==401) else int(''.join(chr(int(l))for l in(49,50-1,50+2)))for i in range(3)]))+''.join(chr(i+int(True*2) if pos==int(str(list(range(0, 101))[-1])[-1]) else i*int(bool(True))) for pos,i in enumerate([95+(((i+1)*10) if i==int(4*5*9/6/1*70==2101) else ((i+1)*10 - 5)) if i==list(range(0, 11))[True<<False] else int(''.join(map(lambda x:chr(x), (int((True+True)**5)+17, (int((True+True)**5)+17+2)-3, int(''.join(map(lambda x: chr(x), ((list(filter(lambda x:x%3==0,range(0, 100)))[18])-int(True),list(filter(lambda x:x%7==0,list(range(0, 100))))[(True*(True+True))**3 - 1]))))))))for i in range(int(3*(2+2!=5)))])))

How does your file structure look like
oh hey love
string
Why u here 
i've always been here
and what's in your Procfile?
YEs you got 
So do u actually pay for winrar
Who doesn't 
Hey just out of curiosity does discord allow bots to set their profile picture per server like the nitro perk does or is still still exclusive to nitro?
You cant even change background profile colour what are talking about haha
Not yet
Okay that’s what I thought because I’ve been poking around for a while and wasn’t sure if it just wasn’t in discord.py yet or if they just haven’t opened it to the api
Exclusive for nitro
discord.py stopped development
Just different color
Thats the accent color
So I heard
everyone has it
You should use another language or use a fork (I don't recommend it)
We're talking about bots
custom banners?
Custom colors
Alternately use a different python library, hikari is nice and not exactly brand new
I’m lookin into other languages now I just wasn’t sure how much was added before it stopped
Haven't seen a bot with a custom picture banner
Just custom color
MEE6 had a red banner a few weeks ago, which is not the most significant color of it's profile picture
I’ve seen bots do a lot of stuff so it’s always worth a ask around … never know what ya may be surprised by…anyway thanks for confirming my suspicions
are you sure?
Yes I am
I've seen it from my own eyes
And pretty sure some others did
So you can ask around and get a confirmation
@slate swan can you hlep mee please
What are your buildpack settings
What exactly have you asked about? I’m a lil late to the conversation
hmmm
Try to create a project again
But this time specify the buildpack before deploying
Do you have a requirements.txt file?
haha just discord
It's not a music bot right
still failed
nah just commands
mmk
Well, create a new project and instantly set the buildpack to Python before linking your github repository
Hmmm it's weird, never seen that before to be honest
@slate swan when mee6's banner was red were u on mobile when you saw that?
should repo be public or it doesnt matter?
Ehm yeah?
Was that a discord bug 
oh.
No that doesn't matter
mhm I asked someone else about it too I think.
It was red on mobile, all I remember
well they said they were on mobile too
can we go in dm krypton
and still is actually
they money hungry 😳
ikr

that's why i never liked mee6
krypton hey can we go in dms
update your discord on mobile
😂
so pricey
everything is payed 😂
ikr
even unb is more cheaper I think
u can't even set a custom prefix without premium
LMAOOO
even a good cheap vps is cheaper than their cheapest option
lmao
I'm on the alpha tester program XD
So it's definitely up to date, and even more than most of the people
3 times cheaper
might be buggy
is the alpha thingy the beta program?
No, there are alpha and beta versions
Alpha
oh
nice
As I said, I can't help any further as I've never faced this issue or seen anyone having it
Yes
what the hell is that? Why would someone pay for mee6
There are many free ones that beat the mee6 easily
Python bot as example
Pretty good replacement
But paying for discord bot is big mistake
I've got a task function in one cog and i want to start it in the main script using on_ready(), but it says that the function is not defined
big mistake
If you happen to pay few bucks it is not that big lost but nearly 90 bucks for a single bot
my bot that has more features including some unique features and even the exact same features mee6 has beats mee6 easily and i payed nothing for it 😂
dang
for 90 bucks that bot better be the best bot compared to any other discord bot, mee6 is far from that
2 heroku accs and 3 free mongo dbs 😎
3 mongo dbs?
for?
in case 512MB isn't enough
Oh
the task needs to be above the on_ready event
although it should be plenty, i just like overdoing things 🤣
I see
at least that way i don't have to worry about the db space 😌
now teach me how to use heroku for discord bot hosting
imagine
I could get a good host for 1 year for free, but I'd like to save them for my API site (if I make one)
Oh, thx I now know how to do it
i loaded the cog before executing the on_ready() event
Kraots typing a essay
-> step 1: make a git repo with all of your bot files
-> step 2: go to your heroku account, create a new app (located in US, will get your average bot latency to under 30ms 100% of the time)
-> step 3: go to settings and add python buildpack, then click "Reveal Config Vars" and add your bot token, along with whatever you have in your .env there
-> step 4: go to deploy, select Github, connect your github account, then select your bot's repo
-> step 5: make sure your bot directory has a file named `Procfile` which has "worker: python main.py" (or whatever the file that runs your bot is) and a requirements.txt where you have your requirements listed in newlines
-> step 6: go to overview, click Configure Dynos and then click that pencil icon and toggle the button then click Confirm
-> step 7: make sure you have 2 heroku accounts and switch between them at the end of each month (when you get an email from heroku saying that you're running out of dynos, they refresh at the start of each month)
-> step 8: done
you asked 🙄
I mean it was half a joke
😔
Not really, thx alot. I may use that to create that
well it still may be helpful to someone 😎
Indeed
shouldnt it be heroku account
both heroku and github
yu said mongo
lol
so I have to keep creating new account?
what does that mean?
.bm A very nice guide.
meaning that at the start of every month, your dynos go back to 500 dynos
even if you get them to 0 during one month, at the start of the next one they'll be back to 500
oh, so is that why you have 2 account?
yeah
but a possible data loss in dbs?
mongodb = server based?
always used mongo 😎
Me who uses JSON 😐
😂
I've got a task function in one cog and i want to start it in the main script using on_ready(), but it says that the function is not defined
can someone help me with this
Eh, well it's preferred when u got an AI and u gotta save it's information in a file
i only use json to store my spam|word filter data 😂
if my bot works as python module, what about then?
Don't... Just start it in the init
will still work
Haha well I also use it for the vote buttons
I see, I may keep pinging you the whole day because you sent the guide
I can show u my JSON file in the disnake server haha
now i regret it 😟
I'mma send that then
you sure will
you don't get pings
???
nothing, forget it. It never happened
there's guides on yt too 😔
yt = bad, pings = good
cutely mutes the server 😎
😂
randomly slides into dms
gently closes dms 😎
ok, this is nicely off topic
yes very much
phew
what about database things?
wdym
connecting to your mongodb?
you need the key which you get from going to your mongo cluster -> connect and then you complete the steps
Ok so first I rewrite my database system on bot
I have sqlite db which can be a problem
How do I count 5 minutes?
I want to print it out like this in ~minutes ~seconds.
using motor to connect in your code: ```py
Docs https://motor.readthedocs.io/en/stable/
import motor.motor_asyncio
cluster = motor.motor_asyncio.AsyncIOMotorClient(MONGO_KEY_HERE)
database = cluster['DATABASE_NAME_HERE']
Then you have 2 ways of accessing one of your collection that you have inside your database, you can either access it as you'd do with a class attribute, or as you'd do with a dict
NOTE: They are all case sensitive
Example 1, dict:
collection = database['COLLECTION_NAME']
Example 2, attribute:
collection = database.COLLECTION_NAME
To see collection methods go to https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_collection.html
import time
seconds = 0
while True:
seconds += 1
m, s = divmod(seconds, 60)
if m == 5:
print('5 minutes')
return
elif m == 0:
print(f'{s} second(s)')
else:
print(f'{m} minute(s) {s} second(s)')
time.sleep(1)
this will print until 5 minutes is reached, then stop
Is there a channel creation callback existent? I cannot find it in the docs unfortunately
I would use it for logging-purposes, that's why
there is a channel creation event
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
Alright, thanks both of you
And you can find the entire list here:
https://discordpy.readthedocs.io/en/stable/api.html#event-reference
So you probably haven't searched at all ¯_(ツ)_/¯
Or haven't payed enough attention as I scrolled ¯_(ツ)_/¯
can somebody help me with creating a discord bot. I am new and I need help with it
Have you learned Python?
How to send messages in local chats of users
You mean private message?
Yes
!d discord.User.send
i have not learned python
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 am completely new
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Start by learning Python :p
ok
And how to get private message that was send to bot?
It fires the on_message event
my bot has another color too
So you can get the content on the same event
i dont think so there is background color
So what?
it was another one more black one like on my another device
it is different on every device
it isn't
it just depends on what discord you use and how buggy it is
mine's appear same for all devices
check if the message.channel is an instance of discord.DMChannel in on_message event
more info about the "banner" colors https://discordpy.readthedocs.io/en/master/api.html#discord.User.accent_color
discord.channel.DMChannel*
or not
i guess that discord.py is dead
well both works
it is
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
api?
What?
I've looked into some d.js and eris codes, seemed messier than dpy
it is
um.. I want to do the reverse of this.
like.. 10 9 8 7 6 5 4 3 2 1..
Ok my creation if not 
Then just inverse the code
ohh
You already got given the code for the other way
then just reverse it, ain't hard, you should be able to do that alone
Just use you knowledge to reverse it
^
Okay
Oh I solved it thanks
what pencil icon?
where's your free dynos tab
still throws the same error that function not defined
Procfile = a specific file?
I've got a task function in one cog and i want to start it in the main script using on_ready(), but it says that the function is not defined
can someone help me with this
i mentioned it in my quick example
Oh I though it was meaning something else
step 5
no, I don't get it
what is ```
"bot has a Procfile which has "worker: python main.py"
create a file named Procfile
oh
there i changed it
save
made it more "explicit"
python -m MyBot would work as well?
The code I wrote below doesn't work.
perhaps
?
oh, good to know. Thx, I will keep pinging you 27 hours a day
no
The code below While True doesn't work, is there any other way?
it works
i even tested my own example
and it worked perfectly
that is only way to run my bot ._.
what are you trying to do, you can use tasks.loop
yeah, but this is for creating a dyno in heroku
mind to explain
if it's the return that errors, then it's bc i thought you'd use it in a function
if you're using it outside the function replace return with break
import time
seconds = 0
while True:
seconds += 1
m, s = divmod(seconds, 60)
if m == 5:
print('5 minutes')
break
elif m == 0:
print(f'{s} second(s)')
else:
print(f'{m} minute(s) {s} second(s)')
time.sleep(1)
yeah
so worker: python __main__.py to use the main file?
no
just worker: python main.py
The code below is activated, but the code below is activated, but the bot doesn't turn on..
whats the file that yu run in cmd
your sentence makes no sense
^
what are you trying to do
I run a folder, because it's a python module
you must have a python file which has bot.run()
which one is that
I do
make a main.py file and import your module
__main__.py
then do worker: Python __main__.py
if your file is named __main__.py then it'll work
The count keeps running and I want to output the count to the bot
Aight, I will try pushing these changes to github
then use @tasks.loop
what do you want to do basically
ur printing the output
yeah
and instead of time use asyncio
you won't even need that
Also u gotta await asyncio or else it wont work
time.sleep puts the whole process to sleep
Yes thats annyoing just use asyncio
Can someone help me with slash commands using http method
if you dk how to do it yourself then consider using a fork of dpy (best one so far is disnake)
btw @slate swan, are you still hosting on somehost?
nope
you got a better one?

hey can someone help me with my
issue
when im running my code locally it works fine but when i deploy it, it throws a file not found error
even though the file is present
show code
just a sec
Umm someone
Why do you need http method
Cuz dpy doesn't support slash commands
#Announcement Creation
message_title = title_msg.content
message_description = description_msg.content
#Field Title = message_field_title
if message_is_embed == True:
if message_has_timestamp:
announcement_embed = discord.Embed(title=f"{message_title}", description=f"{message_description}", color = discord.Colour.blue(), timestamp=ctx.message.created_at)
await announcement_channel.send(embed=announcement_embed)
#If embed has field
elif not message_has_timestamp:
announcement_embed = discord.Embed(title=f"{message_title}", description=f"{message_description}", color = discord.Colour.blue())
await announcement_channel.send(embed=announcement_embed)
if message_has_field:
announcement_embed = discord.Embed(title=f"{message_title}", description=f"{message_description}", color = discord.Colour.blue(), timestamp=ctx.message.created_at)
announcement_embed.add_field(name=f"{message_field_title}", value=f"{message_field_description}")
await ctx.send(embed=announcement_embed)
Im making an announcement cmd. And when i send the embed at the last line,
"await ctx.send(embed=announcement_embed)"
I get the error:
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.name: Must be 256 or fewer in length.
Please help
Im not giving it a big input
just 1 character for title and 1 for desc
Thanks bud
What's the message_field_title
This one is too big
Over 256 characters
It is:
message_field_title = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announcement_creation_channel)
message_field_title is a message object
i use the same wait_for for all the other things
Use message_field_title.content
Doesn't matter
Hi . I wanted to ask how can I put the results we get from a for loop into an embed and not separate each of the results in an embed.
@client.command()
async def seetc(ctx , * , url):
if not "https://" is str(url) or not "http://" is str(url):
url = "http://" + str(url)
else:
pass
result = builtwith.parse(url)
for name in result:
value = ''
for val in result[str(name)]:
name = name.replace('-',' ')
name = name.title()
value += str(val)
embed = discord.Embed(
title = "See Technology",
description = f"{name}" + " : " + f"{value}",
Color = "#6ec21d"
)
embed.set_author(name = "Site Url" , url = f"{url}")
await ctx.send(embed=embed)
like wht do you mean
wait_for("message") returns a Message object, which is over 256 charcaters
put only the content attrribute to your embed
not the entire object
file = discord.File(fr"icons\{image}", filename="image_url.png")
so what will i do
Okay so i put that in the lamda
no
^
do you have those images on your host
Where you did announcement_embed.add_field
yeah
then idk
lemme try
When setting the embed field name
i tried without the rawstring as well, it didn't work
same for description
message_field_title.content = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announcement_creation_channel)
```?
bro
I wanted to ask how can I put the results we get from a for loop into an embed and not separate each of the results in an embed.
@client.command()
async def seetc(ctx , * , url):
if not "https://" is str(url) or not "http://" is str(url):
url = "http://" + str(url)
else:
pass
result = builtwith.parse(url)
for name in result:
value = ''
for val in result[str(name)]:
name = name.replace('-',' ')
name = name.title()
value += str(val)
embed = discord.Embed(
title = "See Technology",
description = f"{name}" + " : " + f"{value}",
Color = "#6ec21d"
)
embed.set_author(name = "Site Url" , url = f"{url}")
await ctx.send(embed=embed)
Please help me
Create a list
Append to the list in your for loop
Then use something like ", ".join(yourList)
Wright I do not speak English very well and I do not understand much. Can you write what you said?
I don't know how to use..
No I won't code for you
Create a list, add elements to the list, get the elements from the list
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'icons\\04d.png'
This the error being raised
the code is
file = discord.File(fr"icons\{image}", filename="image_url.png")```
Basic Python knowledge
Oh. Now I understand. Thank you for your guidance
File is not found, everything's explained
And don't use \ for getting into folders, but /
What does that mean?
it means your supposed to use / for files in folders
So, i am making an error handler that looks something like this:
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error):
"""Handles errors"""
if isinstance(error, commands.CommandNothe heckound):
return
elif isinstance(error, commands.MissingPermissions):
await ctx.send(
embed=create_embed(
title=f"❌ Missing permissions",
description=f"You miss permissions to run this command: {COMMAND HERE}",
uthor_text=error,
color="red",
)
)
How can I reference what command could not be ran due to missing permissions?
ah , works thanks
What is the difference between discord.User and discord.Member?
Self explaining I guess
discord.Member has attributes and functions for guild stuff
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
Okay thanks
ctx.command
okay thanks
I have that, but there is nothing to enable/disable
¯_(ツ)_/¯
So all I need to do is push the Procfile to github, right?
most recent call last):
File "launch.py", line 2, in <module>
from zeenode.load import load
File "/home/runner/Frick/zeenode/load.py", line 3, in <module>
from discord.ext import commands as zeenode
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module>
from .client import Client
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 27, in <module>
import asyncio
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module>
from .base_events import *
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/base_events.py", line 296
future = tasks.async(future, loop=self)
help
pls
yeah it's like that because you're missing the Procfile
me??
no
most recent call last):
File "launch.py", line 2, in <module>
from zeenode.load import load
File "/home/runner/Frick/zeenode/load.py", line 3, in <module>
from discord.ext import commands as zeenode
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module>
from .client import Client
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 27, in <module>
import asyncio
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module>
from .base_events import *
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/base_events.py", line 296
future = tasks.async(future, loop=self)
SyntaxError: invalid syntax
@slate swan help
Well.. fk, heroku does not want to work for me
what's zeenode
after you added it and heroku finished the changes, then refresh the page and it should be there
idk
selfbots are against ToS
doesn't matter, won't help u with selfbots
Wym by heroku finished the changes? And no it is still not there
when it says Build in progress
you have to wait
until it's done with everything
and says Deployed
then it should be there after a refresh or 2
I never saw something like that
Where am I supposed to see it at?
in Overview
you sure you added the github
I'm, just checked it
i literally just made another heroku account for my new music bot and i'm already done, took me less than 3 minutes to set it up
so you defo did something wrong
I spent litteraly 2 hours setting it up
Hmm, how do the bot get the heroku secret var?
😂
i told you
so I prefer somehost..
I mean it is there
go to Settings => Reveal Config Vars => set the key to whatever you want (e.g BOT_TOKEN) and the value to your bot token
os.getenv('KEY')
If discord.User it must enter the user id?
To get a member or user object you need the ID of the user
Regardless of what you want
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Hello! I am making reaction role bot, anf i have some isuess. I will appriciate if someone could help me. Thanks!
Code:
import discord
client = discord.Client()
@client.event
async def on_ready():
print("Logged in.")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utails.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utails.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_rremoves(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_remove(payload):
pass
client.run('TOKEN')```
Error massage. This pops up when i add a reaction.
reset your token...
Yes that too
why
cause if you wont , anyone can use it..
ik
.....
i deleted some letters
as for your error , you used member variable before defining it
Ah cool
so what should definition be
what's your code?
import discord
client = discord.Client()
@client.event
async def on_ready():
print("Logged in.")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utails.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_removes(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_remove(payload):
pass
client.run('TOKEN') ```
guilt
Might want to change that to guild
and you might want to create a variable member set to None by default
so like:
member = None ```?
Well, what do you think?
You coded lambdas but you're not sure about how declaring a variable works

im confused man
man i did member = None
Good then
member is only assigned if role is not None
utails?
fixed
Hello! I am making reaction role bot, anf i have some isuess. I will appriciate if someone could help me. Thanks!
Code:
import discord
client = discord.Client()
@client.event
async def on_ready():
print("Logged in.")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utails.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 898312112944865302:
guild_id = payload.guild_id
guild = discord.utails.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'yen':
role = discord.utils.get(guilt.roles, name = 'Yellow Team')
elif payload.emoji.name == "euro":
role = discord.utils.get(guilt.roles, name = 'Blue Team')
else:
role = discord.utils.get(guild.roles, name = payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_rremoves(role)
else:
print("Member not found.")
else:
print("Role not found")
@client.event
async def on_raw_reaction_remove(payload):
pass
client.run('TOKEN')
utails fixed
!pypi discordutils
DiscordUtils is a very useful library made to be used with discord.py
Still need to fix guilt
ok i am done
obj = {"item" == "fish", "amount" : amount}
users[str(user.id)]["inventory"].append(obj)
except:
obj = {"item" == "fish", "amount" : amount}
users[str(user.id)]["inventory"] = [obj] ```
add_removes(role)
what is wrong with thattt
You have exactlly twice the same code
tf is this?
the dict
^
ok
Spot the difference
in your case "item" == "fish" would just be False
see on first is add_roles(role) which adds role
second is add_removes(role) ehich removes role if i reset reaction


