#discord-bots
1 messages Β· Page 14 of 1
Damn, another reward in your name! GGs
man, please, don't make me laugh
What language is that?
java with maven
Oh well. Compiled languages are on a whole another level π
if channel.name == given_channel.name:
itβs fixed now
ok
@commands.Cog.listener()
# @commands.has_role()
async def on_message(self , message):
if message.author.id == 990358952632021043:
return
await asyncio.sleep(60)
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +10}})```
i want user get +10 after every 60 secconds but this run every time and add 60 yo user , how can i achive 1st
should i go with @vale junco ?
You might be looking for the discord.ext.tasks extension
it gives on_message funtion ?
Sorry?
like if user type something only then he gets money
this think
!discord.ext.tasks
Hmmm
So once a user types something, they start getting money every 60 seconds?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
how feasible would making an image detection bot be for someone who is relatively new to python and discord.py?
How can i make my bot 24 / 7
@tasks.loop(seconds=5.0)
# @commands.has_role()
async def on_message(self , message):
if message.author.id == 990358952632021043:
return
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +10}})```
is this correct ?
5 sec is for testing
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html see here for how to make a basic task loop
if you are new to python, you should focus on learning python, making discord bots is not a very beginner friendly project
hmm alright
!d
no?
Master @silk fulcrum
me
Buy a VPS
and don't think anyone else could
read?
Tutorial
The GitHub education pack offers some free azure and digital ocean credits

That makes no sense
i never was on digital ocean site and found it
Im gonna go to sleep quick 
transfer it there, there will be full explanation
Tomorrow
like if some say hello , it respond right ? i want it respond again after to the same user after a time
sense ?
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
that's not a cooldown, but then sleep func ^^
why do u need that
im UTC+3
Idk that
oof
it will a per user sleep ?\
wtf is peruser sleep
u just respond to that user and that's it
@commands.Cog.listener()
async def on_message(self , message):
asyncio.sleep(10)
if message.author.id == 990358952632021043:
return
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +10}})```
first you didn't await it
done
second you'll get that it will add 10 smth only after 10 secs
i guess you want to give 10 of smth in your economy if user speaks for 10 seconds?
bruh accidental enter
ok i explain what i want u suggest me the correct way
like if a user type something in my chat he get 10 somthin , then second time if he types within a 1 min he gets nothing but after 1 min agin he get 10 somthing π³
!customcooldown
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
wow im stupid
no no i want your approch too
that is actually a thing here
pls
i was typing this:
in __init__ of your cog add self.last_call = dict(), in on_message do ```py
author_id = message.author.id
if author_id == 990358952632021043:
return
now = discord.utils.utcnow().timestamp()
try:
if now - self.last_call[author_id] < 60:
return
except KeyError:
pass
await economy.update_one({"id": author_id}, {"$inc": {"PAODs": +10}})
self.last_call[author_id] = now
but that one is much better
ohhh got cha , π
Also better to disallow bots to enter this economy.
im not even sure if this works, and if so, the dict thing is trash
yo kids it me the nephew of the creator of the dank memer bot!
why ??
Why wouldn't you?
how about partnership :lmfaoo:
its like reword for chat π€ and they can do so may stuff with this
sure but lmao u believed me oof meme material
why do you want bots to earn money? It's not like they can spend it... you'll just be wasting storage
you believed that I believed? i cant believe lmao
no no the user will get money not bot π
@vocal snow
But other bots? (you've only blocked your bot) @limber bison
you know on_message also triggers when a bot sends a message
that id is your bot's id right?
hmm that was big brain move! i appreciate that
aight lets work now!
i ignored it , see code π€
so whats cooking up here?
that only ignoring your bot. Not other bots,
ohhhh got it , thankssss
my favourite soup of Zeffo and someone not getting him
!d discord.User.bot
Specifies if the user is a bot account.
oh ok
is anyone here familiar with bit library?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
is there a way
no
to change a discord bot's banner?
no
bit library relates to discord bot development..
idk 
ehr ip
bitcoin 100000% relates to discord
im using it in discord
no, more
im using pp length generator in discord. is that related to it?
using bit library in discord to track transactions etc
well bad example, agreed...
Dunno seems like a valid point to me.
pp length generator? π

lmao
π tf
Discord tinder bot.
no
ic
probably
π i walked into something weird
you're not supposed to be here
π
nobody except us 
dank has one i think
"pp length generator" ποΈποΈ
frenn
π
you dint see that
hi hi
oh i saw that

because this type of words are not safe)
making my browser scream its unsafe when the website can/uses HTTPS
I didnt I just copied the link from the button itself 
seems like the website doesnt like the word so it made the website unsafe
like*
print("look".replace("o", "i", 1).replace("o", "") + "e")
literal cringe, that's really so cringy
Someone is a pro in coding?
thats what i was aiming for
@slate swan
i think you ment to ping ash
nope
π
Achievement unlocked: Take Aim
π³
Seriously, because i need for help me for all (PS: I'm on phone)
gg
pinging lemonποΈποΈ
I'm totally not going to be off the server whenever lemon sees the ping 


Seriously, because i need for help me for all (PS: I'm on phone)
with what exactly?
just send your problem
we'll help as we can
I don't know python
then we probably won't
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I want to create a bot
master help at all costs
lol
I wanna create a bot in python
master is the best at bot development so.................~~ starts to runπββοΈ π¨ ~~
What?
hey guys, i've gtg
I'm on ANDROID
RN, so gl have fun
Stop
then watch, you have the following problems:
you don't know python
you are on phone
you dont want do much, because you are here asking us
And all together they're unsolvable
ill actually help lmao
wtf
Go || fuck || everyone i just need || fucking || help!
we aren't machines, so why would we do so?
ok, look, without any jokes. go to app store and download an ide for python and app called termux
Then?
if you don't know what ide, then ill find
termux of playstore/appstore doesn't work
yes? bruh
The base package download never does
@rose pelican if you want to start your bot development journey you must learn basic python, resources has allot of good courses for that matter! Then you must learn pythons OOP and just get the hang of it, https://youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc is a good source for learning that and then you can learn disnake or nextcord, which are library to make bots with python, from here https://tutorial.vcokltfre.dev/, if youre on mobile you would use something like replit or even better get on your pc and you could use something like visual studio code!
okimii's such a cutie
machines dont troll either
hello, i was wondering how to add the user name that i am giving and removing the role from, using an f string in the print statement, what method do i use and which parameter do i use (before,after)
@bot.event
async def on_member_update(before, after):
print("----------ZeddyBot is checking for roles----------")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print("----------Giving LIVE Role----------")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID in after._roles:
print("----------Removing LIVE Role----------")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
imagine what was in all minds in this channel (this means my mind)
iirc before and after return member objects
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
so before.name should work?
ashley just know that maybe lemon is always watching, especially you
after!
nome(
wait no, you!
he's wathcing you cus you're too good and too cute
its quite funny putting a bit of terror in ash
oh ok, lemme try that. thanks
dont care 
lol
gtg, bye! went offline
π
how do you make it so that bot commands only work when typed in certain channels?
You can either add a check or a simple if statement
do i have to do that to every single command ?
If you do a check, no. If you use an if statement, yes
Your check is reusable and you can just add a quick decorator so it works anywhere
can you give an example?
Sure, hang on a sec
def is_in_general():
""" A check that only works if the channel is the #general channel (ID: 12345) """
async def predicate(ctx: commands.Context) -> bool:
return ctx.channel.id == 12345 # this will be whatever your channel ID is
return commands.check(predicate)
@bot.command()
@is_in_general() # this is important
async def my_command_1(ctx: commands.Context, ...) -> None:
""" This command only works in the #general channel """
...
@bot.command()
@is_in_general() # notice how we repeated it again?
async def my_command_2(ctx: commands.Context, ...) -> None:
""" This command will also only work in the #general channel """
...
@bot.command()
# nothing here, just a regular old command.
async def my_command_3(ctx: commands.Context, ...) -> None:
""" This command works in any channel """
...
@austere vale
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
I'm guessing they only want certain commands to work in certain channels
oh no i meant all commands-
Then yeah, go for a global check
yeah then my case is the most suiting
ohh okay thank youu
An example of a global check:
@bot.check
async def is_in_general(ctx: commands.Context) -> bool:
return ctx.channel.id == 12345
easy as that
==*
Such a pedant
using a decorator π
they want it for all comandsπ
hes using the wrong operators so no
no i mean π bot.check = func just 'cause yes
oh wait, nononoo im gone im gone
Don't you have code jam to do
if i want to add multiple channels, do i make it into an array
yeah you left a while ago, we'll catch up with your inexistence shortly
you're too cute, he can't keep up i guess
use the in keyword then
and you can just make any iterable
Zeffo slow af π
waht
Nova's the real guy
nova stop worrying about zeffo
No
wont you be worried about your girl
if you had one that is
@bot.check
async def is_in_general(ctx: commands.Context) -> bool:
return ctx.channel.id in (123, 456, 789)
I don't think I will, no
yeah my fault
why not, free money
add a comma after 789 π that ain't a tuple
what
never said it was
Use a set!!
let's use you 
I would rather go play gacha
!e print(type((123, 456, 789)))
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'tuple'>
pretty sure it is
Ashley,
I have double thoughts on how does python even work
okay that worked, that you so much
Use a set though because O(1)
No property
And sets are cool
yeah 
!e py a = 1, print(type(a))
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'tuple'>
imagine caring about time
bruh it actually worked
commas make a tuple, not when its empty tho lol
!timeit
my_set = {123, 456, 789}
print(123 in my_set)
@sick birch :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 702 nsec per loop
Ok then explain ()**2
that works? lmao
!timeit
my_tup = (123, 456, 789)
print(123 in my_tup )
@sick birch :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 539 nsec per loop
No
then 
Our prime minister thinks it does tho.
looks like a tuple is faster
mhm cool
tf is going on
Tuple is faster cause you picked the first element, pick something far deeper @sick birch
** β Today at 1:42 PM** utc -4 moment
why, it's only 9PM
Yes and with more elements!!
don't think that matters
It does lol
Atleast 52 million thousand hundred ids
who in the hell would do that
!timeit
my_set = {123, 456, 789}
print(789 in my_set)
@sick birch :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 709 nsec per loop
!timeit
my_tup = (123, 456, 789)
print(789 in my_tup )
O(1) only matters because it takes constant time to pick element from any depth
@sick birch :white_check_mark: Your 3.11 timeit job has completed with return code 0.
500000 loops, best of 5: 574 nsec per loop
Nova today some CSE final semester guy asked me for code help during his final exam
More bruh.
Do you want to see question
almost the same as last time
More elements, face palm.
hey, how can i open images from discord messages with Pillow?
i want to be able to write a command (not a slash), attach an image to the message with the command and open this image using Pillow. there is no single suggestion how to implement it...
^^
If our tuple had hundreds of elements, then yeah the set would be faster
hehe time comps go brrrrrrrrrrrrrrrrrrrrr
ok
but with relatively few items in the tuple it should be faster
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
ctx.message.attachments for eg
thank you
You can put it in a BytesIO and pass that to PIL.Image.open or whatever
!timeit
my_set = set(range(1, 10000))
print(50 in my_set)
@sick birch :white_check_mark: Your 3.11 timeit job has completed with return code 0.
1000 loops, best of 5: 319 usec per loop
rule 7 
never that set does unpack everything lmfao
What did I just read !
ik just me being an idiot
Oh ok
do you mean like {*range(1,10000)}?
yeah, but forget it lmfao, the classes already unpacks the iterable lol
set, list and tuple all run generators till end
nova going god mode
Not sure if this is the right way to test because range is lazy, so using in lookups are incredibly fast, no matter the size
I sleep goodnight
wdym by lazy lol
When we are watching spirited away
good night you bean
Like 5 in range(1, 10) would not actually do 5 in [1, 2, 3, 4, 5, ...], but it would check if 5 is between the 2 endpoints (1 and 10)
casting the range to a list would fix that
The implementation for range is actually really cool as it does some really nice optimizations
you mean it wont check each element the generator provides?
No, it just checks if 5 > 1 and 5 < 10
,
ohπΏ
Even with a range with billions of numbers, it's blazing fast since it's basic arithmetic
yeah its way better over checking each element and if its the same lol
looks like the range object is implemented in C π¬
π€
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'bot' is not defined```
you ment self.bot
I'll go look at RustPython and see if the implementation is more readable
can someone help?
rustpython as the implementation of python in rust?
@scarlet aurora
right
thats kinda cool lol
i can't read C to save my life π¦

new to discord.py, there are so few actual examples I'm finding on a cursory google, everything says how to respond to a message, cant find how to just send a message to a channel, tried discord.Message().channel('bot-messages').send(self.index) but documentation isnt helpful on parameters for classes and message requires parameters, dunno why that isnt part of the documentation...
you require a VoiceChannel (2.0^) or a TextChannel object or a NewsChannel object, etc. to send messages, you can get those through the discord.Client.get_channel(channel_id) method where channel_id is the channel id and the type is an integer
ok, any good places I should look to get information on patterns/concepts like this? thanks a bunch
The examples are fantastic
if you wanna learn python with OOP then -> https://www.youtube.com/watch?v=ZDa-Z5JzLYM
ah I dont need python help, just understanding how to use discord.py, think the examples will help, the examples i've seen are just like "heres how to respond to someones message" which is great, since you already have a handle on the message which includes the channel
but after that the documentation makes you feel like, welp you know how to do everything with discord.py >.<
any insight why they might not describe the parameters to create discord models? developers not supposed to instantiate them?
Right, you're not supposed to create them
just interact with the objects that the client is connected to got it, think the examples will set me up then thanks
mmm what if a bot is listening/posting to specific channels does the bot:
A) create the channels if they dont exist? (there a way to only allow permissions to create specific channels?)
B) expect admins to create the appropriate channels and not do anything if they dont exist
if it's A what's to limit a malicious bot that doesnt create hundreds of channels?
Yo, I was wondering if there's a display_banner function aswell? Why's there a display_avatar and avatar but not a display_banner and just banner?
what class is display_avatar under?
rust is safer and faster, thanks
It's a property of User and Member object which returns an Asset object
sadly no, there's also a limitation that you would have to fetch a user every time you want to check it's banner
I don't get it. Why's that?
Wasting requests
I dont even care about comparing languages at this point
what documentation is this in? cant find it -.-
it's in the latest branch
!d discord.Member.display_avatar
property display_avatar```
Returns the memberβs display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
well, discord API design
sleep
ashley your a genius right
ew whats that plus it's too early and i havent made dinner
ah ok, thanks
can you make files as an option type for slash commands in discord.py?
no, okimii is
okimii didn't know
didn't know what?
yea just set the type to be a discord.Attachment
I'm not sure but, NVM ash is sm9rt
I thought you typehint discord.File ?
oh god
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
is the documentation through the bot better then the readthedocs? heh seems like it
that's what someone else told me π
the bot webscrapes the documentation from readthedocs site
on dpy server yes
no
I agree that robo danny is far better
I won't be surprised if I'm wrong because I haven't used dpy for 8-9 months
0.o was trying to look at the readthedocs and didnt see the 2.0 info for display_avatar
/latest
i havent used dpy in like 8 monthsπΏ
π why
how is that even possible
bot dev is boring lol
ah i see it now I'm dumb
Actually kinda true
try developing discord
i would, i just dont want to have a stroke reading css
π
I'm talking about a chaos IRL
css π
imagine making bots, you guys dont even deserve a life anymore 
bro what
π
Imagine
and electron.js is just beautiful
youre beautiful
π₯Ί
actually js itself is beautiful
i would disagree
imagine crying on css, just get better at writing css
gonna repost this sorry:
what if a bot is listening/posting to specific channels does the bot:
A) get manage channels permission and create the channels if they dont exist? (there a way to only allow permissions to create specific channels?)
B) expect admins to create the appropriate channels and not do anything if they dont exist
if it's A what's to limit a malicious bot that doesnt create hundreds of channels?
JS makes me wanna yeet myself from a building
an itachi with a weak eyesight
Oh yeah my fault
i had 3 friends who rejected, blocked me because im coding on python, and they're JS. They did that, of course they did not fully make discord, but most of it
Blocked for writing python code?? π
i havent used my mangekyo but i can on youπ³
yes, they were like 13 years
But did they actually know js
pythons elegancy and readability is something elseπ
i guess yes
idk what to say but you saved yourself from JS so it's better

if you use python youre instantly attractive, its proven because sarth exists
π

i tried JS, i coded a bot, but I felt disgusting, and decided myself to not continue this shit, and rather they block me than I'll continue those if (bruh) {stuff}
well as long as you use json
you're technically a js person 
use yaml
lmao
imagine not using a text file for a config
what monsters ya'all are
just an exception
nope
what all can you use .count() for?
!d itertools.count
itertools.count(start=0, step=1)```
Make an iterator that returns evenly spaced values starting with number *start*. Often used as an argument to [`map()`](https://docs.python.org/3/library/functions.html#map "map") to generate consecutive data points. Also, used with [`zip()`](https://docs.python.org/3/library/functions.html#zip "zip") to add sequence numbers. Roughly equivalent to:
```py
def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
while True:
yield n
n += step
``` When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: `(start + step * i for i in count())`...
example/info
well that's what most languages use actually
use the same file extension as the current and import file mehh
guys i did everything, this code was running in my other pc, but its throwing this error in my laptop.
i am building a Music Bot
i dont know. I used java and php and i didn't feel that disgusted, just a litle bit annoying to forget ;, but with js, idk
maybe that's cause of them
incorrect bot token
invalid token rwad the error
ohh, okay will change it again
yeah most languages use curly brackets({}) for scopes/code blocks over depending on indents, like python, yaml also for config files etc
sarth im not directing the info at you, its with you
try rust π·
thankyou so much guys, i had been looking at the code for more than last 20 mins, thanks so much for help @slate swan @slate swan
atleast rust screams at you, YOU MISSED A COLON MY BROTHER
no problem
I didn't find any languages using indentation other than python, Lua, ruby and julia
rust always got ur back
yeah but ruby uses an end keyword to end scopes of a function which is kinda cool ig
i still wouldnt use it but yesπ«
julia does the same, Lua too
mhm cool
nah i dont have time
pause the time
how
i always say i dont have time, ~~continues to watch yt videos for 5 hours straight ~~
well maybe I have, but the problem is that I have a month to make my bot from almost nothing
why
cus its august
and
i've lost june and july cus of chess tournaments

and after august goes september, and school, and exams
reject school
i'd like to
accept python as your new loverπ«
but parents won't let me
ok im going to stop messing around
where will I go? live?
self.process
self.process?
whats error, i see squiggly line
and add a self argument lol
who was faster?
maybe its static
from my side, me
idk about discord
he would use @staticmethod
from my side, me
I should've said that 
we cant see what's up there
it's first line we see
well just call it with ClassName.process then
but you canπ
how
π
self arguments!
add self as the first parameter in instance methods
i name my instance arguments sarth
so i can do
sarth.give_love_to_okimii()
sarth has been initiated in that exampleπ³
AttributeError
setattrπ
slots
add self in the process fn
Yeah,.
y9 is an expert in oopπ³
I wish man
yes, and add self as the first argument in that function.
isnt it referred as method
yes
i love you
./distract.png, it's in the same dir
βrelative pathsβ
everyone just want me out this chat smhπ
codejam is not important right now
keyboard went brrr
ill assume you're aware how path strings work?
im leaving, slides slowly to sarths dmsπ
I just wrote it there...
./distracted.png
try entering the full relative path
righ4 click and you will see an option for copying relative path, click on it and paste the path there
where did you right click? should have done on the file
okimii broke my heart, im leaving, i cant handle this anymore((
π
ππ
so no one responded to my question earlier about bots interacting with specific channels and if it's proper to either give bots permissions to manage channels vs having the server admins create the channels manually
Yes it can be done, but why? its like a 2 second job for a person to do it. Lol. But yeh give what ever permissions and code you want to write for your bot and utilise, nothings stopping you.
just kinda worrying that people install bots with manage channels when it could potentially ruin their server
Then use a popular bot, they tend to be a lot more secure.
I mean, I'm trying to make a bot, and trying to make it secure. Popularity doesnt mean something is secure
and I am trying to find repos that do something similar to what I want, just not finding it quickly
popularity brings reputation
Well, yes they do as the teams behind them have better coding experience than most people, and have much better security in place to protect their data, they have a reputation to upkeep so have security always on there minds.
What is it you want.
BUt yes, you can use the manage channels permission, with https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.create_text_channel in your code, if your bothered about security then you can create .env file for your discord token and store it there and reference it in your code as you more than likely know, and don't publicly expose it, you can go even further if your using a DB and put that on to its own instance and have the bot connect remotely to the DB.
I want my bot to listen to and post messages to specific channels, but dont know how to interact with a guild that might not have those channels set up
so the options are have the bot require manage channels (which I find unsafe), or have the admin create the channels manually
You'd have to check if the channels are created if not create them with the bot
Or if the channels are not created post some sort of message to the admins to manually create the channels
yeah, was also trying that route but i'm trying to find out how to query admins which is pushing me into other permissions roles like Intent.members which I guess thats fine
but was hoping to find a simpler path for user/developer that felt safe to me
If you absolutely will not use manage channels permissions on the bot, then you're gonna have to just have the bot post some sort of message if the channel(s) are not found
kinda wish they at least split manage channels into create/edit/delete permissions
π€·
I just see someone installing a bot and boop all channels are deleted
Well that is irrelevant, cause if a user gives your bot admin to their server on invite then they are at risk either way, and a lot of people do it just for simplicities sake.
Yeah
and admins are not developers so they wont look at code or know what stuff does
But they can still nuke servers.
Just dont think the public is that aware or not concerned that installing bots might have that happen, dunno
just seems important to me
yeah I know, I think I can sort stuff like that out, just has been driving down a rabbit hole of 'there has to be a better way'
Ok then, have it message admins to creat ethe channels if your bothered about security π
<@&831776746206265384>
!cban 906176958772158464
:incoming_envelope: :ok_hand: applied ban to @brittle swift permanently.
thanks
speaking of malicious actions >.<
that was a user not a bot who posted that link
yeah but was kinda on topic π
Welcome to the world of the internet... Lol, but anyway back to your problem. Giving a bot manage_channels permissions do have its draw backs and security risks, mostly coming from the developers lack of security, this is also the case for if you give a bot full admin, your pretty much screwed especially if you have your token leaked.
If you don't want to go down the road of giving your bot permissions to create the channels, then you would have to make it messages admins to create the channels for example, please create Channel1! and Channel2!
So long as the code matches the name of the channel your listener should also work, unfortunately the actual code would be a bit to complicated for me to actually write.
Sounds about right
I mean there are much more things to think about to in regards to security, like where is this bot hosted, replit? heruko? a VPS on DigitalOcean or some other hosting provider? Does it have a DB? If yes, is that DB on the same server? If yes, move the DB on to its own server with only traffic open between the 2 servers, Is there a public IP on your server? If so, is there a firewall in front with traffic locked down to your IP/VPN? Lots of things to think about to help get your Discord bot more secure.
uhh its not replying to the right message
code:
@commands.command(name='poll', description='Creates a poll')
async def poll(self, ctx, *, question):
"""Creates a poll."""
embed = disnake.Embed()
embed.title = 'Poll'
embed.description = """{ctx.author.name} asks:
{question}
***React with β for yes, β for maybe, or β for no.***"""
await ctx.send(embed=embed)
await ctx.message.add_reaction('β')
await ctx.message.add_reaction('β')
await ctx.message.add_reaction('β')
What do you mean by "replying"?
reacting*
Yeah ctx.message is the message that triggered the command
Use the message returned from ctx.send()
oh... how would I fix that lol
huh?
would
react = ctx.send()
react.add_reaction("emoji here")
work?
@sick birch ^
also use f strings
yeah ik i forgot the f
Is there a way to detect when someone reacts to a reaction and then edit the message (bot sent) they reacted to?
can a bot get someone's roles without role perms?
how do i make python discord bot send a random gif from giphy (using giphy api) to discord when run bot command?
Read the API docs?
i cant find it?
The GIPHY Developer Portal is how you integrate the world's best GIF API into your business, app or project.
thanks bro
heya quick question, is it compulsory for message content intent to be enabled to use a bot
If you have traditional prefix commands, yes
is there a way around it tho
No
so I have to wait till 31st august
async def giphy(ctx, *, trending):
response = await session.get('http://api.giphy.com/v1/gifs/search?q=' + search + '&api_key=mygiphyapitoken&limit=25')
gif_choice = random.randint(0, 24)
await ctx.send(gif_choice)
await session.close()```
Why does my code not work? giphy api, random gif
can a bot get someone's roles without role perms?
yeah it can see them
just like normal members can see eachothers roles
well no. What do you mean "take"?
like just get a list of his roles righjt?
oh yes. Yes.
not actually take lol
it wont let me invite my bot to my server
@commands.command()
async def name(self, ctx, name: discord.Member):
mongo_url = "mongodb+srv://WolvTMG:(pass)@tmg.fiztp.mongodb.net/?retryWrites=true&w=majority"
cluster = MongoClient(mongo_url)
db = cluster["LunarVigil"]
collection = db["Names"]
print(name.id)
data = collection.find_one({"_id": name.id})
await ctx.send(data)```Why is this sending an empty message?
mygiphyapitoken did you replace this with your token?
yes
async def giphy(ctx, *, trending) -> None:
session = aiohttp.ClientSession()
response = await session.get('https://api.giphy.com/v1/gifs/random?/api_key=apikeyhere')
data = json.loads(await response.text())
embed = discord.Embed()
embed.set_image(url=data['data']['images']['original']['url'])
await session.close()
await client.send_message(embed=embed)```
this is the updated version of my code. but still not working?
error:
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "randomgif" is not found
try aliases=["randomgif"] instead of name="randomgif"
More detail would be helpful
wdym "doesn't work"? does it not invite? do commands not work?
"doesn't work" could be a hundred different things that are wrong, it's almost impossible for us to tell w/o more info
hmm... by "doesn't work", do you mean that your computer is catching on fire whenever you generate the URL?
ok so i go to oauth2 and url generator
i select bot > administrator and use my redirect as https://discord.com
i invite the bot and then it does nothing
That's the problem
You shouldn't have to fill in a redirect URL
That's only if you're doing a log in with discord type thing
I can do it just fine
how do i fix it
What did you select for the scope?
async def giphy(ctx, *, trending) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=apikeyhere&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
how to get this working? its not work
@slate swan
breh...
it is giphy api
Okay.. but what's the issue?
it doesnt work
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "randomgif" is not found
it shows this error
That's strange, can you try the <prefix>giphy?
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "giphy" is not found
You sure you saved it?
yes i did
And you're sure you don't have any other instances running? (e.g on the production server)?
no
No as in you're not sure, or no as in you're sure you don't have any other instances running?
Im sure that i dont have any other instances running.
in dpy 2 i want to make a button name be a variable this is what i try py class Moves(View): def __init__(self, ctx, moves): super().__init__() self.moves = moves self.ctx = ctx @button(label=self.moves[0])
I think reset your token, just to be 110% sure, because there's no other reason that it could be doing that
You don't have access to the self variable in the decorator scope
Perhaps try going with a more dynamic approach by subclassing button?
could it be the other parts of my code, thats causing it?
Doubt it
is class?
It is a class, but you'll want to subclass it
anyone know?
what is @ for
It's a decorator
in pycord can you have a dynamic cooldown with a slash command
ello got some dumbass error and i cant figure it out
Traceback (most recent call last):
File "c:/Users/sbpc/Documents/Lite-lite/_bot.py", line 19, in <module>
async def works(ctx):
File "C:\Users\sbpc\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 914, in decorator
result = command(**kwargs)(func)
File "C:\Users\sbpc\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 1551, in decorator
return cls(func, **attrs)
File "C:\Users\sbpc\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 604, in init
validate_chat_input_name(self.name)
File "C:\Users\sbpc\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 1621, in validate_chat_input_name
raise ValidationError(
discord.errors.ValidationError
just hoping someone could help
hello, how would i had a timestamp in the print statements, im guessing using the datetime module? or sys?
@bot.event
async def on_member_update(before, after):
print("----------ZeddyBot is checking for roles----------")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print(f"----------Giving LIVE role to {after.name}----------")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID in after._roles:
print(f"----------Removing LIVE role from {after.name}----------")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
datetime module probably your best bet
so using fstring {datetime.time} ?
hmm actually datetime.datetime would be better. so i get the day month year format too
that's not a valid token
weird
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.
import discord
from discord.ext import commands
Client = commands.Bot(command_prefix='.')
File "/Users/sketch/vscode/workspace/Bot/main.py", line 25, in <module>
Client.run('no')
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/client.py", line 723, in run
return future.result()
how do you format datetime.now() id like to drop the ms
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
thank you, i found it after a semi non efficient google, lol
i made this.. looks like it works..
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
i have to plug it into my print statement for my discord bot now
does that make any sense at all?
@bot.event
async def on_member_update(before, after):
print(f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}----------ZeddyBot is checking for roles----------")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print(f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}----------Giving LIVE role to {after.name}----------")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID in after._roles:
print(f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}----------Removing LIVE role from {after.name}----------")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
hmm, im getting invalid syntax?
you can't have same type of quote in fstring
oh, geez.. thanks w
Would be better to use discord timestamps here
hmm, wdym? it's a print statement for the Linux terminal my bot runs on, 24/7. it's not meant to print to discord
Oh yikes, didn't notice. My bad. Maybe try the logging module?
hmm, looks like it's working fine so far. will see if i actually get the usernames printed out tho. but so far so good
@bot.command()
async def look(ctx):
embed=discord.Embed() embed=discord.Embed(title=f"{ctx.author} searched a ",random.choice(place),"and found a ",description=random.choice(items),color=0xffff00)
embed.set_footer(text="Look π Command ! Dev - vd#7157")
await ctx.send(embed=embed)
Idk how to resolve the error.
How can I delete all channel with my bot?
I cant find my code but you can look it up on google.
why does the message.content prints empty?
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
print(f'{message.guild} | {message.channel} | {message.author}: {message.content}')
the rest seems fine but the content wont show
did you define it ??
like the discord.Message
yes it does that
Are you on 2.0)
Oh yeah i see π
im using the slash commands branch
no problem haha
You need to enable message_content intents
oh
the bot is verified so it would be kinda rough to do that
it was just a test anyways
thanks
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
you can check the channels of the guild and you can pick one
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
how come this doesn't work? ```py
@client.event
async def on_guild_join(guild):
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
await channel.send('I will send this message when I join a server')
break
I pulled the code from stackoverflow but it seems fine to me
any errors?
well I don't know why
you don't do guild.channel
you do guild.text_channels
and there is such an attr
did you save the file? or maybe you sent not actual code?
Can someone help?
Please.
why is all embed stuff inline?
use f strings with the random.choice
youre passing unnecessary arguments with the usage of commas
How to fix??
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
also what is this
π
it works now π sorry for the trouble
lol
I guess I forgot to save the file
pycharm π
@primal token Stil cant fix it.
whats your error?
do you know how I could change it so that it could create a text channel
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
π
@primal token
as told, youre passing unnecessary arguments with the usage of commas.
use your f strings and pass it in to curly brackets, idk how theyre called
Bro you asked what embed=discord.Embed() means π
these {}?
f"my name is {arg}"
ty
{ these? @primal token
i asked why are there two definitions of them in one line
Thats dumb
you guys missed my entire point, its frightening
@primal token im hella tired rn please jst show me what it should look like
@bot.command()
async def look(ctx):
embed=discord.Embed() embed=discord.Embed(title=f"{ctx.author} searched a ",random.choice(place),"and found a ",description=random.choice(items),color=0xffff00)
embed.set_footer(text="Look π Command ! Dev - vd#7157")
await ctx.send(embed=embed)
new to py ig
just pass your expressions into curly brackets?
Im not.
it seems like thats a lie
i just cant function correctly.
Im new to discord.py just not py
@cold tide
its a invalid amount of arguments error, its not even related to discord.py
a lot of begginers think like that if they were coding on python like 2 months or learnt simple basics of syntax
no offense, but even having a brain fart you should know how to navigate yourself which such a descriptive error
Yeah lol
I have certain issues which make that harder π
at least I was like that :lemao:
who wasn't lol
i just havent slept for 2 days
i don't think that's the issue
"no offense"
that has no participation in this conversation...
π€
Learning python before working with a advanced library is essential non the less.
answer in ur face btw
he literally has expressions in the f strings, he answered himself lol
i wouldn't call it advanced, maybe that's cause I'm too familiar with it, I started my whole python career with it
Theres 350+ lines in my bot i know what im doing. Im not sitting here waiting to be spoonfed i just want the code.
Its advanced as it depends on OOP and async programming?
intermediate python programmers could easily familiarize themselves with discord.py
@cold tide py embed = discord.Embed(title=f"{ctx.author} searched a {random.choice(place)} and found a", description=random.choice(items), color=0xffff00) see? no commas around random.choice, that's all
maybe without OOP though lol
oh, that's how it works, then maybe
Thankyou some idiots cant do that.
More lines of code dont make you any better, in fact less lines and clean code is what actually matters
It is lol
π€
Im not sitting here waiting to be spoonfed i just want the code
i just want the code
isn't that basically asking to be spoonfed
I have almost 2000 lines in my mod cog, and I can't make it smaller( am I dumb?((
@dusky pine bro stop π₯ π΄
seems like your code base and architecture arent exactly perfect
what should I do? I have ... I don't remember how much commands, but not a little I promise you
i think you can add other cogs to cogs
and a couple of listeners
Wah
good job :lemao:
it depends on many things
@cold tide i feel rather kind today.
we all know you are new to Python, its very clear from the error you're getting.
However not to worry.
discord.Embed(title=f"my name is", name, "what is ur name")
this is wrong, title only takes ONE argument.
Fixed code:
Embed(title=f"my name is {name}, what is ur name?")
Also having 350+ lines doesnt matter
Im not new to py. Just discord.py
ratelimits....
I think the confusion comes from the print function which takes multiple arguments
im not new to JS guys, im just new to DJS
stop telling us you arent new
this is the same as telling an f1 driver you can drive a car, when you only have a bike license lol
Is put time.sleep(1)
ofc
anyways its fixed so goodbye, i did understand what @primal token was saying my brain just cant function properly rn.
it still doesnt matter, you shouldnt use time.sleep either way.
Whay
admit the fact youre new to python, learning the fundamentals of python is necessary to take on a discord bot project with python
because there is asyncio?
asyncio.sleep()
you really need to stop lying to yourself
Im not new and thats the truth. I may need to get used to discord.pys syntax since ive only been using py but im still learning.
this is for your greater good
You understood what i said but couldnt implement it and then proceeded to ask to get spoonfed, interesting.
For the 6th time.
My bot died
discord.py syntax? lmao
You know what i mean.
discord.py has no syntax, its the same as other libraries
yk what i mean.
no
theyre called library abstractions, not syntax.
this is what happens when you brute force python just to use it with discord.py for a discord bot
but i think we're getting a little too rude
Guys, why are we arguing here, let's make a fund and buy MEE6 :lemaoX3:
Ive just told you all i havent slept for 2 days and i havent took my medication, which is why you dont understand what im trying to say.
welcome to the gang
Maybe worry about your health over your discord bot
i do.
clearly not XD
i like coding as a hobby and it supports my mental health.
like a distraction.
i cant get my medication right now other wise i would.
we're getting off topic here
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
what's your issue @cold tide ?
just another day in this channel
already fixed
ah
Well... not really
but i cant be bothered
Ill just ask my dad when hes up.
but thankyou for the help ig
pov: your dad is Danny
He would archive you
why not mine((
π
and unarchive you with breaking changes later
nope my dad just codes like me. He gets paid to build websites etc
he has way more knowledge than me + a 1 to 1 would be more benefical.
well, same, but mine doesn't code websites
for sites?
imagine making websites and not using js/ts
funny how CSS wasnt mentioned
isn't that what a lot of people do? they just use some good lang for that, like php idk and use libs, but not clean js/ts
im not sure tho
that's not the way, only html means only visual nothing else
and you need at least CSS so it would look nice
yeah ^^
offtopic
whocares
Were not gonna get arrested are we?? π₯²π₯²



what'd I do
** **