#discord-bots
1 messages · Page 729 of 1
Yeah no problem
ok add ur code
import os
token = os.getenv('token')
bot.run(token)
and u r done
for replit
remove quotes and try like thispy client.run(os.getenv(token))
u have to add ' before token
what do u need
hmm
import os
data = os.getenv("token") # gets the value associated with the key token
bot.run(str(data)) # just to be sure, we explicitly cast it into a string
str? no need of that too
just add bot.run(data)
it would work
hm i tested it i am a proffesional py bt dev and currently working on antinuke bot of mine fastest antinuke
;aw;
Okay.....
@client.event
async def on_guild_member_update(oldMember,newMember):
try:
guild = oldMember.guild
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update).flatten()
logs = logs[0]
reason = "Upadted Member As Non-Whitelisted User"
await logs.user.ban(reason=f"R-Dynamic Protection System | {reason}")
except:
pass
is this correct?
for banning members on adding roles
Dine it works.
Thank you so much to all
np
Never have bare try except
ohk
This is a bad practice
Your errors get eaten up and you don't know what's happening
Use traceback to print whatever errors that occurs when someone happens
!d traceback.print_exc
traceback.print_exc(limit=None, file=None, chain=True)```
This is a shorthand for `print_exception(*sys.exc_info(), limit, file, chain)`.

In some cases where you know the error doesn't matter, you can bare try excepts but most of time, you should always try except for specific Exceptions
is there a way with disnake slashcommand to add more description for optional?
even tho it self-described but would like to specific it with "The message you would like others to see when tag you."
@KortaPo#8459 ok i would remove btw tell me if it works
u can but u have to have them as secrets
You need add description to optional argument
You can use a docstring to add description to your argument and disnake will parse it from your docstring
For example
yes example 🙂
this is what i have now ```py
@commands.slash_command(description="Show others that you are Away From Keyboard.")
async def afk(self, inter, *, message="no reason given."):
while we also on it is it possible to have aliases for slashcommands?
@untold token bro tell
i watched it but idk why but i was getting an error so i setup my repo using github desktop
@lapis breach what do u need
@bot.slash_command(name="test", description="stuff")
async def func(inter: disnake.ApplicationCommandInteraction, input: str = "stuff"):
"""
...
Parameters
--------------
inter : disnake.ApplicationCommandInteraction
Stuff here
input : str
your description for input here
"""
# rest of your code
@honest vessel this is one way to add descriptions
trying to instll discord 2.0
Another way is
@lapis breach oo
from disnake.ext.commands import Param
@bot.slash_command(name="test", description="stuff")
async def func(inter: disnake.ApplicationCommandInteraction, input: str = Param(description="your description here", default="stuff"):
# rest of your code here
so i can use discord buttons
@lapis breach hm
You can't have .env files on replit, secrets are the way, yes although you can use a bare nix repl to bypass that
Tell what
What error
how... also can you make buttons without discord.py 2.0? it would be much easier that way
not possible
you can but it's not recommended
@lapis breach i dk how to create py buttons
You can use third party libraries to create buttons for dpy version below 2.0
@untold token how to remove all role bro from a certain user
But as i said, it's not recommended
ohh ye then how do i upgrade my discord.py???
Get the list of role objects, loop through them and remove it
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
You need to use the github development version
@untold token bro remove role from a particular user like await newMember. remove_roles
now?
how.
I did not understand what where you trying to say
what libraries?
The same command as above
discord-components
@untold token thank you that was badass perfect!
No problem
Can a bot create_invite on somebody other's name?
no lol
i... already have that library.... i installed it to try to get it
You should read the disnake docs
guess ill use that then
@tidal hawk but it can give an already created invite from another user
What's the best method for determing who invited a user into a guild?
I literally told you how to do it
You just need to loop through
I am not going to spoonfeed you
Also aren't you professional python bot developer?, you should know this by then
Iterate through the invites list and see who's count increased?
Currently this needs quite a few hacks to get working due to Discord API limitations.
i know bro
Then you can do it
btw proff at js actually py intermediate
.
Bruh?
can someone help me with a bot that says "pong" if i type /ping
ive een trying for 2 days and i just get errors
You need to create a command with the prefix /
i cant connect my bot to my ode
Is it a slash command or text command
If it is a text command using the commands framework then
@solar anchor
@client.command()
asyns def ping(ctx):
await message. channel. send("Pong" )
may be this u nees
!code
would't commands with prefix / be annoying af always get the built-in slashcommans showing up
ohl
unless you are too fast
well then another prefix idgaf
@bot.command(name="ping")
async def ping_command(ctx: commands.Context):
await ctx.send("pong") # sends the message where the command was invoked
but i cant connect my bot to my code
Did you call the run() method?
i have a fetish of having . as prefix
client = discord. client( command_prefix='/',)
!d discord.ext.commands.Bot.run
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
Roughly Equivalent to...
.
how do i connect my bot to my code???
hmm
if i do import discord it gives errrors
what is the error
then you havnt installed library correctly
discord.Client() has no keyword argument as command_prefix
how do i do it correct
You need to use commands.Bot aka, commands framework
use pip
This is a good example
@solar anchorwhat error did u get?
@solar anchor u need this
intents=discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix=commands.when_mentioned_or("/"), case_insensitive=True, intents=intents)
That is in the python REPL
that is python interpeter
^
what do i do
Ctrl+z and enter
and then?
py -m pip install discord
@untold token yep sory
Also, how familiar are you with Python?
sorry abouy that
no pip
your still in the python interpeter...
See those >>>?
decent, i just cant get it to work ffs
close it
mhm?
You are trying to run the code through a python REPL
That means you are in the python interpreter / REPL
discord.Intents.all() already enables all the intents needed
why doesn't await channel.edit(slowmodde_delay=seconds) change the slowmdoe? No errors, no eh's
os.system("pip install discord.py")
Typo on mode?
which means?
@solar anchor close it open new cmd 🙂 and type the command he gave u
slowmode
not slowmodde
seconds
close visual studio?
import discord would work
it doesnt
If you are on vscode, you can press CTRL + `
Damn
That opens a new terminal
okay done
I was expecting an error atleast
now what?
py -m pip install discord
@spring flax what is ur cmd
now type the command he gave u
yayy
xD
its installing!
@solar anchor hmm nice
nice
@velvet compass wont import discord work?
now turn on matrix themesong clubbed to death 😄
After it is installed, sure
hm btw they r same lmao
Its not a built in
It's a third party library
It needs to be installed
i only use import discord to install discord.py
First
and it works
Sure
right
on replit?
@untold token ya
i would love to see python put discord.py as core library 😄
where was that example?
do anyone know the lang nextcord?
Because replit has UPM (universal package manger) which reads your imports and guesses your libraries and installs it for you
@untold token hmm
nextcord isn't a lang, it's a fork of discord.py
yep
nvrm found it
btw its is better than dc py
its same lang tho
um guys
i am swapping from discord.py to disnake
Yeah disnake is much better
Pretty normal
but
Yeah your library has installed
@solar anchorrun that pip update it askes for 😉
The warning is just that your pip is not updated to the latest version
pip updates all the time, so that is a pretty common message to update to the latest and greatest
o
py -m pip install --upgrade pip for windows (using the py launcher is very handy)
^
happy hakking
haha
So are we still "fkn useless"?
sadge
Who said that
i did in general cuz ive been struggling with this for 2 days
i apologize guys
its still yellow
idk
didn't u restart vs code?
i did not
do it
he said do it!
lawl
i did it!
take a kneel
it works (:
@solar anchorall wanna be ur friend now when u making awesome bots your friends gonna be like 🤤
lmaoo
(motivation speech)
and be ready to buy a wig, cause you gonna ripp of some hair in frustration when get errors / stuck
but this place always helpful

lmao i know, ive been coding with C#
ah, then this should be way easier
no brackets only tabs 😄
cool
didnt make a new boom like minecraft?
simple concept huge potential crazy game
lmao i wish i was good enough to make a game like that
ill send u a vid of me speedrunning my game
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
its not long
can someone help me?
RuntimeWarning: coroutine 'Command.__call__' was never awaited
with open('balance.json', 'r') as f:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\mdsuy\OneDrive\Documenten\DarkEmpireBot\currency.py", line 127, in on_message
with open('balance.json', 'r') as f:
AttributeError: __enter__
My code always worked but when I tried to reboot my bot today this error came
Code?
@client.event
async def on_message(message):
if message.author.bot == False:
with open('balance.json', 'r') as f:
users = json.load(f)
await update_data_bal(users, message.author)
await add_experience_bal(users, message.author, 1)
await level_up_bal(users, message.author, message)
with open('balance.json', 'w') as f:
json.dump(users, f, indent=4)
await client.process_commands(message)
this always worked till now
it works like this, if someone says something in the chat it adds + 5$ to their discord balance
Hmm
Although I would say this is not a good way for leveling up
its not a leveling command
If someone spams messages, its still going to count
true, but I'm new in python someone said I had to do something with timestamps but didn't do it yet
I don't see any problem in this code though
Although I will suggest improvements
First of all
use an event listener
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
So for example
you're clearly using a json as db 🤢
@ruby tinselRuntimeWarning: Enable tracemalloc to get the object allocation traceback this usally (when using async) means u didnt await it
bro I only have 100 members in my discord, I don't need a bigger db
the error is actually first line
RuntimeWarning: coroutine 'Command.call' was never awaited
i use json for AFK system, and database for streamers+check if live n update etc
json isn't a db, that's the problem.
size doesn't matter || in programming ||
json is a textfile thats all 😄
json is for config
its working for me 💀
@client.listen()
async def on_message(message: discord.Message):
if message.author.bot:
return
with open('balance.json', 'r') as f:
users = json.load(f)
await update_data_bal(users, message.author)
await add_experience_bal(users, message.author, 1)
await level_up_bal(users, message.author, message)
with open('balance.json', 'w') as f:
json.dump(users, f, indent=4)
# await client.process_commands(message)
# no need to call this method as, it's an event listener and it's not overriding the default message event
until it doesn't anymore, then you'll lose everything...
and yes
Do not use json as a database
Its not meant for it
If you really want a database similar to json syntax, use MongoDB
this is clearly just a YT video...
i use json for simple afk system with msgs, but would't store data that is very important like xp, balance, etc
Which one
the code you shared from him
look at the function names... that's textbook YT
Oh that
then i was correct, said it was nvr awaited 😄
Probably yes
I made the function names myself
kek
you're inspired by a YT video, don't tell me you're not
inspired yes
Also, you should use event listeners rather than event as they are external and asynchronous
You can have multiple listeners of same event type and they will not interfere each other
you basically have the same implementation, which is bad
I didn't copy paste, I was just checking for cool idea's
I mean, it does look like its copied
you just retyped and implemented some of his methods
json as a db for example
Which is a very bad practice
put in aiosqlite in it !
^^
and u set
Json is a format used to transfer data and communicate between different programming languages, servers, APIs, etc
It's not meant to be used as database
download DB Browser (sqlite) and create ur tables with GUI if u dont wanna write sql to create database n tables
right, then use an async wrapper for that db and you're all set
aiosqlite
alright
I suggest u to use mongodb cuz mongodb is a nosql db
(its ok use json n learning, they prob find flaws later on anyway)
Nosql databases are ez
why would't u wanna learn SQL? 😄
I already installed SQLite 2 weeks ago
im just lazy ngl 🥷🏾
sqlite is handy if on same host
you will have most painful problem when doing relationship between stuff btw
unless you know what ur doing
Mmm like wut 🤔
i dont know what examples to pick 💀
to fit that right, thats just what i heard from sql smarty pants
but eh, i wouldn't recommend ppl to use mongoDB for other reason, mainly because mongoDB developers not documenting things rights, so you have to use shitty drivers for it to work
But look sql has select but mongodb works like json 🤡thats why i love mongodb
ikr json is simple as hell, but what is problem with using select ? atleast you'll learn something 🤔
True but yeah mongo is ight
yep
rip
it means user is none
either remove =None or add if statement to point it to author when nothing is being passed
@tacit token
not work
not work what
you'll make it work
simply by removing the *, in your avatar parameters
Remove *, and mention a user
oh i didn't notice that
he's also confusing himself by calling a member object a user
he's developing bugs, let him be
heloo,
im not the best programmer but I made an json to embed obj parser in python and thought it may be cool to share haha :3
For me its pretty useful, since I like to design embeds on https://discohook.org but they only show the embed as a json obj (at the bottom)
Its my first package ever, so please don't hate :3, you can find the package here: https://pypi.org/project/dj2e/
You can install it via pip install dj2e
(discord json 2 embed)
And use like the following example:
from discord.ext import commands
import js2em
bot = commands.Bot(command_prefix="!")
@bot.command()
async def test(ctx):
embeds = js2em.jsonToEmbed('test.json')
# jsonToEmbed takes a file-path and returns a list of all embeds in that json
await ctx.send(embed=embeds[0])
bot.run(token)
Hello everyone again can someone help me how can I find API, I mean from which site, for improving the bot feature. I have tried to find it, but not able.
anyone have command ideas?
is this what you're looking for? https://discord.com/developers/applications/717511790514405416/bot
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
do you have an event in that cog?
try removing commands.Context
if that doesn't work double check if your cog actually got authenticated to the bot its self
def setup(client):
client.add_cog(nameOfYourCog(client))
if that also doesn't work then im not sure what could be causing this
show the cog
ok so a command isnt found right?
or whats the error
by?
the command isnt found?
show me the full cog
in ban you forgot the self argument
to access the class
and your indentations arent correct
they should be indented with the init
delete 1 level of indentation
oh yeah they are
i have a question about mongoDB it gives me this traceback idk why it takes my on_ready command as a database object
Traceback (most recent call last):
File "d:\Scripts For Python\Discord Bot-20211230T010404Z-001\Discord Bot\discordBotCore.py", line 37, in <module>
async def on_ready():
TypeError: 'Database' object is not callable
im clueless 💀
thats the issue there is no object it should be calling
the database goes online normally, but then it doesn't launch the bot due to that
and then ends the script there
yea my on_ready command
event*
sure thing
client = pymongo.MongoClient(connection, serverSelectionTimeoutMS=5000)
try:
print(client.server_info())
print("Connection Established!")
except Exception:
print("Seems like something went wrong connecting to the database.")
@client.event
async def on_ready():
change_status.start()
print('Bot Core Status: Ready!')
the connection var is my database
and all that works fine
then it detects my bot code as apart of the database
nope
o 💀
change the variable name to something else 🤷🏾
how can bot change a members nick?
i only find permissions check
should be like edit_member(nick="poop")
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
^ @honest vessel
yeah i found it but now this
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
bot has manage nickname on
in roles
I don't recommend a bare exception.
await user.edit(nick=str(user.display_name)+str(" (afk)"))
Who's nickname are you trying to edit?
user = await inter.guild.fetch_member(inter.author.id)
Role of the member higher than the bots?
^
You sure the error is from the edit?
yes
<disnake.interactions.application_command.ApplicationCommandInteraction object at 0x7f30b6de9580>
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
user. Is user a member object or user object?
member object
user = await inter.guild.fetch_member(inter.author.id)
should i do fetch_user?
maybe
No
but it should say has no agttribute this is about permissions
permissions are fine
Just a nitpick but the variable name should be member
Can you invite an alt to your server and try your command on it?
Or anyone with no roles/only member role
@final ironu got a point but
I can say bot has all perms, ON
and top of heriarchy
yet permission fails
bot itself intents = disnake.Intents.all() intents.guilds = True intents.members = True intents.presences = True intents.typing = True codewise
You know that inter.author is already a union of Member and User right? This means you don't need fetch_member at all.
anything i need to activate on dev.discord?
@slate swanok but that we can fix later 😄
whatsup with the permissions
Bot has no permissions
it has all
You can say whatever you want, the API doesn't lie
Nope
then wtf
As I said above, invite an alt and try it
ama do a dumbie function just change nick n see
Well, you're trying to nick yourself right?
i am trying to use slash command and bot is supposed to change my nick
And you probably have the server ownership right?
Server ownership is bigger than everything
Bot can't nickname an owner, so there you go :p

You can't pass to a bot
Only a limited amount, yeah

how could i make a command that will make the channel nsfw
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Set the nsfw kwarg to True.
You also need to await it since it's a coroutine
and put decoration on that command with has_permissions()
also check if it already is true, if it is dosame but put False
n u got a switch
ye
that will turn all channels possible for nsfw tho
if one see u type that they can type it in another chan
n change chanperms
@commands.command(aliases=["ub"])
@commands.has_permissions(ban_members=True)
async def unban():
pass #un-ban
``` this has a permission check if the poster "author" has bermissions of ban users (not bots permissions)
Anyone know how to use hikari?
I personally have not even looked at it. This video may be good. https://youtu.be/xc1VpbRd4is
In this video, we go over the basic setup steps for creating a discord bot in python.
Let me know in the comments what videos you want to see next.
INSTALL PYTHON: https://www.python.org/downloads/
DISCORD DEVELOPER PORTAL: https://discord.com/developers/
HIKARI GITHUB: https://github.com/hikari-py/hikari/
HIKARI DOCUMENTATION: https://www.hi...
hey anyone know the installation for pycord?
bc i need to know the proper command so i don't install the wrong one
!pypi pycord
https://pypi.org/project/py-cord/ lookin for this?
wh....why?
so i don't install the wrong package
thnx
no...why....why pycord?
bc it's good
!pypi disnake
this
!pypi nextcord
A Python wrapper for the Discord API forked from discord.py
true lmao
datetime.datetime.utcnow.replace(microsecond=0)
File "main.py", line 77, in on_member_remove
await channel.send(f":outbox_tray: [{datetime.datetime.utcnow.replace(microsecond=0)}] **{member}** ({member.id}) ha salido del servidor")
AttributeError: 'builtin_function_or_method' object has no attribute 'replace'```
why do i get this?
utcnow(), you need to call the function
so only datetime.datetime.utcnow()
datetime.datetime.utcnow().replace(microsecond=0)
thanks!
yo ```py
await channel_admin.send(embed=verificationAdmin)
msg = await channel_admin.send(embed=verificationAdmin)
await msg.add_reaction("❌")
await msg.add_reaction("✅")``` produces this error
In name: Must be between 1 and 100 in length.```
anyone got an idea why
its all indented properly
im saying for the actual code it is
oh
done
@commands.command(name="finish")
async def finish(self, ctx):
for i in range(0,len(Json_Items)): #It doesn't exist
for x in Json_Items[i]:
if int(x) == int(ctx.message.author.id):
if len(Json_Items[i][x]["User IGN"]) > 0:
if len(Json_Items[i][x]["Ps"]) > 0:
Json_Items[i][x]["user_verification"] = True
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)
this doesn't have the code that you sent earlier
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)
for guild in bot.guilds:
for channel in guild.text_channels:
if str(ctx.author.id) in str(channel.name):
verification = discord.Embed(title = "Verification", description = ctx.author.mention, color = discord.Color.green())
await ctx.channel.purge()
ign = Json_Items[i][x]["User IGN"]
verification.add_field(name = "ID", value = ctx.author.id, inline = True)
verification.add_field(name = "IGN", value = ign, inline = False)
paymentMethods = ' | '.join(Json_Items[i][x]["Ps"])
verification.add_field(name = "P M", value = paymentMethods, inline = False)
verification.add_field(name = "STATUS", value = "Completed")
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
await ctx.send(embed=verification)
await channel.edit(name=f"{ctx.author.name}-Completed-{channel.name}")
await ctx.channel.send("This channel has been **archived** and is waiting on judgement from our <@&915363576867344435>")```
alr
channel_admin = bot.get_channel(928357998559105095)
verificationAdmin = discord.Embed(title = "Verification", description = ctx.author.mention, color = discord.Color.dark_red())
verificationAdmin.add_field(name = "ID", value = ctx.author.id, inline = True)
verificationAdmin.add_field(name = "IGN", value = ign, inline = False)
paymentMethods = ' | '.join(Json_Items[i][x]["Ps"])
verificationAdmin.add_field(name = "P M", value = paymentMethods, inline = False)
verificationAdmin.add_field(name = "STATUS", value = "Waiting")
await channel_admin.send(embed=verificationAdmin)
msg = await channel_admin.send(embed=verificationAdmin)
await msg.add_reaction("❌")
await msg.add_reaction("✅")```
there
any idea?
brb
😭
how do you make server only commands
what's the problem
wdym?
!d disnake.ext.commands.guild_only
@disnake.ext.commands.guild_only()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
okay, thanks :)
ok
I recommend learning a bit more about async programming and databases.
https://vcokltfre.dev/tips/storage/
imo I dont like hot chocolate
what is disnake tho?
fork of dpy
does it work with dpy?
U need to remove await channel_admin.send(embed=...)
the .guild_permissions
Ig
basically dpy but they continue it
If you use discord you can just replace disnake with discord
guild.only
and replace it with?
replace anything to do with discord with disnake
alright
thanks guys
why?
But you need to import commands anyways so you should already have it
I should but like json kinda good for me rn
Have you heard of mongo? Json based database.
Using motor you can make it async.
yeah i have commands imported
I have not
anyone here knows how to make bots work in threads?
Then it's just ```py
@commands.guild_only()
what even is the problem
yeah
Threads? What do you mean?
do i just have to add guild = "guild id" up in my code?
that new sub channel feature
Ohhh i was thinking about threading lol
its osmething to do with the adding the reaction cause like I removed the await and tried it with a simple message, same error
oh okay haha
In name: Must be between 1 and 100 in length```
alright
Don't think discord.py has that.
okay
property threads: List[disnake.threads.Thread]```
A list of threads that you have permission to view.
New in version 2.0.
Do recommend using it.
yeah ill probably change to disnake
Awesome :)
try user.avatar.url
hey so i gotta make a bot only allow messages in a certain channel that start with the command prefix(!) + qna , if the message does not, the bot will delete that message pls help
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
@bot.event
async def on_message(msg):
if channel.id == 928397708149030923:
if ``` thats what ive come up with so far
its not a method btw, its a property
i was thinking about msg.startswith("qna")
yeah
You can dictate what messages are processed by your command handlers by overriding on_message
It sort of acts as a gate to your command handlers
how?
And else: await ctx.message.delete()
If you do not process_commands() at the end of on_message, then that command will be ignored
You can use that to your advantage
By dictating what messages get processed and what are ignored
how would dictate what messages get processed?
if statements
py@bot.event async def on_message(msg): if channel.id == 928397708149030923: if msg.content.startswith("qna"): print(works!) ? like that
sure that would work but none of your commands would work
You'd need to process_commands()
thats not good
okay
@unborn prairie.commands?
sorry for the ping lol
can’t he just use commands instead of events ?
on_message is the first thing that's called before any commands are processed, so you can do some funky things like editing the message.content. This way d.py thinks you sent one thing while in reality you sent something else.
Same concept with picking which messages progress to the command handling portion and which are ignored
You can drop the message before d.py even realizes that there is a message
ahh
@sick birch could you give me a example? please
yeah, that would help
on_message:
if something is True:
process_commands()
else:
# do nothing, thereby ignoring the message effectively
on_member_join provides you with discord.Member, not discord.User
okay, so with @bot.command or what
No, an event
kk
data = user.avatar.read()
here try this
user.avatar returns a Asset obj and it has an inbuilt .read method
Why the spoonfeed
i can almost hear you selecting all and copying it lmao
Also there's really no need for .resize or any imaging libraries
d.py provides a native method to get the url in a certain format
This is pre 2.0 btw
@bot.event
async def on_message(msg):
if msg.channel.id == 895072295146651709 is True:
if msg.startswith("qna"):
print("qna message!")
print("is in correct channel")
process_commands()
else:```like that?
ah okay, but my other commands will still work right?
as long as you have process_commands()
also i suggest you refer to the documentation for that as you've got it wrong
also msg.startswith() will not working considering msg is of type discord.Message, not string
yeah i should probably do that
msg.content?
you got it
you could use user.avatar.with_size(size).read(), as robin said
I recommend making a bot not a client then.
what if i wanna use process_commands for print?
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
isnt that the same thing
No.
?
That's not how it works
But i can see you already made a bot, can i see how you created that variable?
process_commands actually starts up the command handler
It starts up the process where it figures out which command you called, which function to call, parsing args, etc...
How? It's just a coro
sure
bot = commands.Bot(command_prefix="!")
but its await process_command(message) so it sends a message right
No it does not send anything
It only starts up the command handler
Without it none of your commands will work
So you can also just do this ```py
@bot.command(name='test')
async def test_cmd(self, ctx):
if ctx.message.channel == 895072295146651709:
await ctx.send('Hello!')
else:
await ctx.send("Wrong channel!")
!test will trigger this command then.
Yeah but they only want those commands to work in a certain channel
Then make the check in the command
aight
But if you want to have a global check you can do that as well
Preference ig
@bot.event
async def on_message(msg):
if msg.channel.id == 895072295146651709:
if msg.content.startswith("qna"):
print("qna message!")
print("is in correct channel")
await process_commands()(msg)
else:```
Not quite
process_commands() takes one argument, the message instance
it's not a function that returns a function
I would strongly suggest you learn asyncio and the basics of python
Can you pass msg? Though it was fixed.
The exact name i mean
He uses msg instead of message
yeah i probably should
My method would be easier for starters :3
@bot.command(name='test')
async def test_cmd(self, ctx):
if ctx.message.channel == 895072295146651709:
await ctx.send('Hello!')
else:
await ctx.send("Wrong channel!")
Oh no you just have to pass in the message instance
Problem with this is
You'd have to do that in every single command you have
Which in a larger scale could get quite painful
You could just make a check for it then.
But like he said you can either do a global check or on_message()
global checks are more flexible
but for this case an on_message() will do unless you want to be fancy
I'd prob use disnake.ext.commands.Cog.cog_check then
There's really no advantage of using one over the other in this instance that I can think off the top of my head
But on_message() only works for filtering what messages get passed through, global checks are much more flexible
For example they can check who sent the message, etc...
i give up lmao my 2 braincells cant comprehend this
That's why we got 3
Or 4
Maximum 5 for the luckiests
I'm making a bot and I need it to get the last image that was sent in the chat. How can I do this?
basic python is the minimum
discord.py is not a beginner's library by any means
a firm understanding of the language is strongly recommended before diving in with the library
I.. don't recommend doing this lol
Only if you would have some kind of cap.
You have 2 options:
- loop through all the messages till you find an image (more intensive)
- every time an image is sent, save the message's ID somewhere (less intensive)
How would you recommend getting the image to the bot?
Like the last idea, using a dict.
Ok
redis :D
True but with Redis you would earn 1 extra brain cell
you guys have braincells?
no i dont
thought it was just me
huh
panda
you used bot.command() yet used the self param
I couldn't hold myself back from pikaing you
here you go 
wat
oh
yes, weird
and
if ctx.message.channel == int_object:
is freaking me out
@cloud dawn you can't keep that message like that
Oh lol yeah i should sleep
@haughty quartz```py
@bot.command(name='test')
async def test_cmd(ctx):
if ctx.channel.id == 895072295146651709:
await ctx.send('Hello!')
else:
await ctx.send("Wrong channel!")
@haughty quartzAll commands or just !test?
where is your bot.event since you can stop it there
from discord import Message
@bot.listen()
async def on_message(message: Message) -> None:
if message.author.bot:
return
if message.channel.id == 895072295146651709:
if all([
message.content.split(' ')[0][0] in bot.command_prefix,
message.content.split(' ')[0][1:] in [cmd.name for cmd in bot.commands]
])
await message.delete()
wait what does -> None mean
It returns nothing
Habit
I could shorten it but i want to satisfy other programmers and readability.
says that the function returns nothing
sort of like:
public static void myFunction() {
}
so what if there's still a return something
It doesn't matter
Well tbf you can never return nothing
!e
def myFunc() -> str:
return 5
print(myFunc())
@sick birch :white_check_mark: Your eval job has completed with return code 0.
5
¯_(ツ)_/¯
lies
Are you trying to kill me
typehint is nothing more than a comment to python unless devs decide to take advantage of it
Typescript is much better in that aspect
you were killing us with the test command
I fixed that
no

I did
cog params in main file command
I just thought he wanted something else
once double quotes, once single quotes in send(), killing programming habits
it was a menace 
Basically any statically typed lang
Python can be strongly typed as well though
can i ask a question regarding slash commands here?
are slash commands related to dpy and its forks?
bot = commands.Bot(command_prefix='/')
Minecraft commands
Hahaha yeah, i'm actually going to call it that now in my bot
yes
Your mad you dont know the syntax smh
If andy doesn't know the syntax the package most likely has no docs
FR
Well tbh in python that is pretty doable
await channel.send("text", file=kwarg)
Depends on the project
Like, for an example good luck on reading the source code of Qtile as pseudo documentation
cv2
what was this thing that runs every specified time (seconds, minutes) like it runs every 30 seconds and does smth
a task?
yw lol
how can i get a guild in a task like i need in for user in guild.users:
Is it a specific guild?
yea
Depends on the task
But you can just do bot.guilds.
yw
its just one guild i could specify with an id
Yea
But you need to add wait_until_ready
Since tasks start before the cache is populated
where
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
At the top of your task code
okay but how do i get a specified guild in a task
smt like ```py
guild = [guild for guild in bot.guilds if 267624335836053506][0]
bot.get_guild is faster
#hardcoding
Since it's dict getitem which is O(1)
true
so bot.get_guild(id)
Yes
thx
Does that even get updated anymore?
i would just use a fork tbh
guess not xd
dpy doesnt have timeout for members and it doesnt have buttons tbh just use a fork which is a full package
It's archived isn't it
Yes.
Kek
oof
Thank god, garbage library design

Indeed
They use the wait_for to hook onto button presses
nope... but i tried updating and it didnt work so... i guess im kinda stuk
Meaning you can only wait for 1 in any command at a time
And if you want to wait for any amount you must spawn that many Futures
Since that's how wait_for works
Only reading this hurts my soul
gives me a stroke
Also blocks until Future is set
so... no1 can help me right?
i would recommend a fork tbh
disnakeeeee
what that?
!pypi disnake
:)
i already got most of my code in the older version do i have to rewrite it?
correct
Most likely not
Jeez okimii giving them the scare
but disnake gets maintained sooooooooooooooo
so... just some teaks?

You'd change the namespace which you access models and methods from
discord -> disnake
import disnake as discord
do they subclass view?
Don't disnake's button use Views as well

yah
Yes
panda really
🙏
😂
to many beers for tonight
Only 1 i gotta work tomorrow
yeah yeah
I swear ;-;
f
oof
i dont remember how i fixed that the other time
python -m pip
py -m pip install disnake
so many ways lol
k thx
Yeah same for tensorflow but i got 3.10 for discord bot
for me 2.7 uses python and 3.9 uses python3
You can alias it
wait... i installed this on a project witch has discord.py.... is this a problem?
idk seems cursed
~ive never used python or discords api so... im kinda new
i havent updated cuz pylance has a stroke with 3.10
Same but i don't want to skip versions since that is even worse.
but is there?'
python 3.10's pip installation on Ubuntu was broken on the earlier release lol
No, they have different namespaces
Just don't get disnake and discord mixed up
Ubuntu 😔
should i change anything on my imports?
Don't blame me , was considerablely new to linux
You gotta change all discord stuff to disnake
I want to comment more..
or just install Disnake as Discord
😳
In your venv
2060 seems a bit op for a console app
🏃♀️ shifted to Kali Linux now
Arch is pog though
how to get information from API :v i forgor
You got the 16gig variant :3
What api?
Yea
Using aiohttp
Most probably you'd me making a req using aiohttp
ok, thanks for hint
not that bad , I'm comfy with Linux now so..
and I don't need to do anything too windowish
Either way you can just setup a KVM with GPU passthrough running windows on redhat drivers
Yeah it would be a aiohttp request and you'd use .json() to get the dictionary it shows while opening the web
Imagine running a virtual machine in 4gb ram
ok, not find anything on google, more hint pls
k
https://docs.aiohttp.org/en/stable/ first seach result
how to make web request with discord bot
HOW TO REACT
smol
Ah
async with aiohttp.ClientSession() as session:
res = await session.get("url")
json_data = await res.json()
what packages to install and import
Well , just import aiohttp, u don't need to install it
It's installed with discord.py
no need import JSON?
Why import json
also how to get spesific (what the heck is the name of this (the one in bold))
{"id":"36","data":"blahblahblah"}
It's a dict, you access the key
how to do
isn't it needed...?



